Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 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.  
  7. namespace ConsoleApplication9
  8. {
  9.     public class TopSort
  10.     {
  11.          List<int>[] Edges;
  12.          int N;
  13.          int[] Color;
  14.          public int[] Numbers;
  15.          Stack<int> Stack = new Stack<int>();
  16.          public TopSort(List<int>[] graph)
  17.          {
  18.             Edges = graph;
  19.             N = Edges.Length;
  20.             Color = new int[N];
  21.             for (int i = 0; i < N-1; i++)
  22.                 Color[i] = 0;
  23.             Numbers = new int[N];
  24.          }
  25.         public bool topological_sort()
  26.         {
  27.             bool Cycle;
  28.             for (int i= 0 ; i < N; i++)
  29.             {
  30.                 Cycle = dfs(i);
  31.                 if (Cycle) throw new Exception("В графе есть цикл");
  32.             }
  33.             for (int i = 0; i < N; i++)
  34.             {
  35.                 Numbers[Stack.Pop()] = i;
  36.             }
  37.             return true;
  38.         }
  39.         public bool dfs(int v)
  40.         {
  41.             if (Color[v] == 1) return true;
  42.             if (Color[v] == 2) return false;
  43.             Color[v] = 1;
  44.             for (int i = 0; i < Edges[v].Count; i++)
  45.             {
  46.                 if (dfs(Edges[v][i])) return true;
  47.             }
  48.             Stack.Push(v);
  49.             Color[v] = 2;
  50.             return false;
  51.         }
  52.     }
  53.     class Program
  54.     {
  55.          
  56.         static void Main(string[] args)
  57.         {
  58.             List<int>[] mas = new List<int>[4]
  59.             {
  60.                 new List<int>() { 3 },
  61.                 new List<int>() { },
  62.                 new List<int>() { 1 },
  63.                 new List<int>() { 1,2},
  64.             };
  65.             int[] num = new int[4];
  66.             try
  67.             {
  68.                 TopSort ts = new TopSort(mas);
  69.                 bool b = ts.topological_sort();
  70.                 foreach (int i in ts.Numbers)
  71.                     Console.WriteLine(i);
  72.             }
  73.             catch (Exception e)
  74.             {
  75.                 Console.WriteLine(e.Message);
  76.             }
  77.          
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement