Advertisement
vovanhoangtuan

TopoSort

Apr 27th, 2021
779
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.76 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace Bai3
  9. {
  10.     class Program
  11.     {
  12.         static int n;
  13.         static bool[] visited;
  14.         static List<List<int>> adjList = new List<List<int>>();
  15.         static LinkedList<int> res = new LinkedList<int>();
  16.  
  17.         static void Main(string[] args)
  18.         {
  19.             readFile("TopoSort.inp");
  20.             DFS(1);
  21.             writeFile("TopoSort.out");
  22.         }
  23.  
  24.  
  25.         static void writeFile(string fileName)
  26.         {
  27.             StreamWriter sW = new StreamWriter(fileName);
  28.             foreach (int item in res)
  29.             {
  30.                 sW.Write(item + " ");
  31.             }
  32.             sW.Close();
  33.         }
  34.  
  35.         static void readFile(string fileName)
  36.         {
  37.             StreamReader sR = new StreamReader(fileName);
  38.             n = int.Parse(sR.ReadLine());
  39.             visited = new bool[n + 1];
  40.             for (int i = 0; i <= n; i++)
  41.             {
  42.                 adjList.Add(new List<int>());
  43.             }
  44.             for (int i = 1; i <= n; i++)
  45.             {
  46.                 string temp = sR.ReadLine();
  47.                 if (temp == "") continue;
  48.                 string[] split = temp.Split();
  49.                 foreach (string a in split)
  50.                 {
  51.                     adjList[i].Add(int.Parse(a));
  52.                 }
  53.             }
  54.             sR.Close();
  55.         }
  56.  
  57.         static void DFS(int u)
  58.         {
  59.             visited[u] = true;
  60.  
  61.             foreach (int v in adjList[u])
  62.             {  
  63.                 if (!visited[v]) DFS(v);
  64.             }
  65.             res.AddFirst(u);
  66.         }
  67.  
  68.         static void TopoSort()
  69.         {
  70.  
  71.         }
  72.     }
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement