Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- namespace Lab3
- {
- public class Node
- {
- public Dictionary<int, int> edges = new Dictionary<int, int>();
- }
- public static class DictionaryExtensions
- {
- public static void AddOrChange(this Dictionary<int, int> dic, int key, int value)
- {
- if (dic.ContainsKey(key))
- dic[key] = value;
- else
- dic.Add(key, value);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- var text = File.ReadAllText("in.txt").Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
- File.Delete("out.txt");
- int it = 1;
- int n = int.Parse(text[0]);
- var nodes = new List<Node>();
- for (int y = 0; y < n; y++)
- {
- nodes.Add(new Node());
- for (int x = 0; x < n; x++)
- {
- it++;
- if (int.Parse(text[it - 1]) < 0)
- continue;
- nodes[y].edges.Add(x, int.Parse(text[it - 1]));
- }
- }
- int startNode = int.Parse(text[it]) - 1;
- int endNode = int.Parse(text[it + 1]) - 1;
- /*********************/
- var weight = new Dictionary<Node, int>();
- var pathNodes = new Dictionary<int, int>();
- var visited = new Dictionary<Node, bool>();
- foreach (var v in nodes)
- {
- weight.Add(v, int.MaxValue);
- visited.Add(v, false);
- }
- weight[nodes[startNode]] = 0;
- foreach (var v in nodes)
- {
- Node currentNode = null;
- foreach (var minNode in nodes)
- if (!visited[minNode] && (currentNode == null || weight[minNode] < weight[currentNode]))
- currentNode = minNode;
- if (weight[currentNode] == int.MaxValue)
- break;
- visited[currentNode] = true;
- foreach (var nextEdge in currentNode.edges)
- {
- if (Math.Max(weight[currentNode], nextEdge.Value) < weight[nodes[nextEdge.Key]])
- {
- weight[nodes[nextEdge.Key]] = Math.Max(weight[currentNode], nextEdge.Value);
- pathNodes.AddOrChange(nextEdge.Key, nodes.IndexOf(currentNode));
- }
- }
- }
- /***********************/
- if (weight[nodes[endNode]] == int.MaxValue)
- {
- File.WriteAllText("out.txt", "N");
- return;
- }
- else
- {
- File.AppendAllText("out.txt", "Y\r\n");
- int currentNode = endNode;
- var path = new List<int>();
- while (currentNode != startNode)
- {
- path.Add(currentNode);
- currentNode = pathNodes[currentNode];
- }
- path.Add(startNode);
- for (var i = 0; i < path.Count; i++)
- path[i]++;
- path.Reverse();
- File.AppendAllText("out.txt", string.Join(" ", path) + "\r\n");
- File.AppendAllText("out.txt", weight[nodes[endNode]].ToString());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement