征程开始,前路漫漫啊,我相信,我会站在巅峰!
要温习温习前两天学习的东西了,贪多嚼不烂,所以这一周复习,tarjan,三种最短路,特别是贝
尔曼,spa,再看看dinic,一些想法要去验证一下,再看看二分匹配,应该一周就过去了吧!
ok! 开始,先是tarjan, poj 2186,典型的强连通题,题的实质意思就是一个n个点的单向图,
给出路,问图中是否存在所有点都对他可达的点,有的话输出这样的点的个数!没有就是0!很简
单吧!因为在有向无环图中如果有且仅有一个出度为0的点,那么图中所有点对这个点可达!
那么,我们的任务就是求出图中的强连通分量,然后把它看做一个点就可以了(所谓的强连通分量缩
点)!
代码
1 #include<stdio.h>
2 #include<string.h>
3 #include<stack>
4 #include<iostream>
5 using namespace std;
6 struct Arc{
7 int h,t,hl,tl;
8 };
9 struct Arc arc[50005];
10 struct Node{
11 int date,f_in,f_out;
12 };
13 struct Node node[10005];
14 int n,m,map[10005],s_out[10005];
15 int dfu[10005],low[10005],cur;
16 stack<int> s;
17 int re;
18 void init()
19 {
20 int i;
21 for (i = 1; i<= n; i++)
22 {
23 node[i].date = i;
24 node[i].f_out = 0;
25 }
26 for (i = 1; i<= m; i++)
27 arc[i].hl = 0;
28 }
29 void tarjan(int id)
30 {
31 int i,k;
32 dfu[id] = low[id] = cur++;
33 s.push(id);
34 map[id] = -1;
35 k = node[id].f_out;
36 while (k != 0)
37 {
38 if (map[arc[k].t] == 0)
39 {
40 tarjan(arc[k].t);
41 low[id] = low[id]>low[arc[k].t]?low[arc[k].t]:low[id];
42 }
43 else if (map[arc[k].t] != -2)
44 low[id] = low[id]>dfu[arc[k].t]?dfu[arc[k].t]:low[id];
45 k = arc[k].hl;
46 }
47 if (low[id] == dfu[id])
48 {
49 int t = 0,t_out = 0,sum = 0;
50 memset(s_out,0,sizeof(s_out));
51 while (t != id)
52 {
53 t = s.top();
54 s.pop();
55 sum++;
56 k = node[t].f_out;
57 while (k != 0)
58 {
59 if (s_out[arc[k].t] != -2)
60 s_out[arc[k].t] = id;
61 k = arc[k].hl;
62 }
63 s_out[t] = -2;
64 map[t] = -2;
65 }
66 for (i = 1; i<= n; i++)
67 if (s_out[i] == id)
68 t_out++;
69 if (t_out == 0)
70 {
71 if (re == 0)
72 re = sum;
73 else re = -2;
74 }
75 }
76 }
77 int main()
78 {
79
80 int i,j,k,x,y;
81 while (scanf ("%d%d",&n,&m) != EOF)
82 {
83 init();
84 memset(map,0,sizeof(map));
85 memset(dfu,0,sizeof(dfu));
86 memset(low,0,sizeof(low));
87 for (i = 1; i<= m; i++)
88 {
89 scanf ("%d%d",&x,&y);
90 k = node[x].f_out;
91 if (k == 0)
92 {
93 node[x].f_out = i;
94 arc[i].h = x;
95 arc[i].t = y;
96 }
97 else
98 {
99 while (k != 0)
100 {
101 if (arc[k].h == x && arc[k].t == y)
102 {
103 i--;
104 m--;
105 continue;
106 }
107 j = k;
108 k = arc[k].hl;
109 }
110 arc[j].hl = i;
111 arc[i].h = x;
112 arc[i].t = y;
113 }
114 }
115 cur = 1;
116 re = 0;
117 for (i = 1; i<= n; i++)
118 {
119 if (map[i] != -2)
120 tarjan(i);
121 if (re == -2)
122 break;
123 }
124 if (re == -2)
125 printf ("0\n");
126 else printf ("%d\n",re);
127 }
128 return 0;
129 }
130