HDU ---Legal or Not

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 
 5 const int maxn = 500+10;
 6 vector<int>map[maxn];
 7 int save[maxn];
 8 int index[maxn];
 9 bool used[maxn];
10 int n, m;
11 int flag;
12 
13 //初始化
14 void init()
15 {
16     for(int i=0; i<=n; i++)
17     {
18         map[i].clear();
19     }
20     memset(used, false, sizeof(used));
21     memset(index, 0, sizeof(index));
22 }
23 
24 //输入
25 void Input()
26 {
27     int a, b;
28     for(int i=1; i<=m; i++) //注意是m条边的输入
29     {
30         scanf("%d%d", &a, &b);
31         map[a].push_back(b);
32         index[b] ++;  //入读加一
33     }
34 }
35 
36 //查找入度为0的点
37 int find_zero()
38 {
39     for(int i=0; i<n; i++)
40     {
41         if(!used[i] && index[i]==0)
42             return i;
43     }
44     return -1;  //存在环
45 }
46 
47 //剪掉所以先驱为k的点的边
48 void cut(int k)
49 {
50     for(int i=0; i<map[k].size(); i++)
51     {
52         index[map[k][i]]--;
53     }
54     map[k].clear();
55 }
56 
57 //执行拓扑排序
58 void topology()
59 {
60     int k;
61     for(int i=0; i<n; i++)
62     {
63         k = find_zero();
64         if(k != -1)
65         {
66             cut(k);
67             used[k] = true;
68             save[i] = k;
69         }
70         else
71             flag = 0;//存在环  
72     }
73 }
74 
75 int main()
76 {
77 
78     while(cin>>n>>m && n+m)  //n个点 m条边
79     {
80         init();
81         Input();
82         flag = 1;
83         topology();
84         if(flag)  //无环
85             
86             cout<<"YES\n";
87             /*for(int i=1; i<=n; i++)
88             {
89                 printf((i==n)?"%d\n":"%d ", save[i]);
90             }*/
91         else
92             cout<<"NO\n";
93     }
94     return 0;
95 }

 

posted @ 2012-09-08 10:45  另Ⅰ中Feel▂  阅读(155)  评论(0编辑  收藏  举报