在线评测:
http://codevs.cn/problem/4511/
整体思路:
说白了就把这看成一张图,找一个大小不为1的最小的强连通分量即可
失误之处:
没啥失误,但是回忆tarjan还是有些慢,所以再来理顺一边,首先tarjan需要dfs对吧。然后得把dfn,low值,入栈bool搞一下吧,然后找边吧,边指向的边若是没访问过,那就搜!!!!如果在栈里,那就直接拿dfn更新就行啦~否则啥都不做。画个图就懂啦!!
体会心得:
平时好好复习啦~
AC代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>#include <stack>using namespace std;int head[500000],nxt[500000],to[500000];int n,tp,sum,cnt,minn,tot;int dfn[500000],low[500000];bool instack[500000];stack <int> zn;void cr(int s,int t){ sum++; nxt[sum] = head[s]; head[s] = sum; to[sum] = t;}void dfs(int x){ zn.push(x); instack[x] = true; cnt++; dfn[x] = cnt; low[x] = cnt; for (int tp = head[x];tp;tp = nxt[tp]) { if (!dfn[to[tp]]) { dfs(to[tp]); low[x] = min(low[x],low[to[tp]]); } if (instack[to[tp]]) { low[x] = min(low[x],dfn[to[tp]]); } } if (dfn[x] == low[x]) { tot = 0; while (zn.top() != x) { instack[zn.top()] = false; zn.pop(); tot++; } zn.pop(); tot++; if (tot != 1) { minn = min(minn,tot); } }}int main(){ scanf("%d",&n); minn = 999999999; for (int i = 1;i <= n;i++) { scanf("%d",&tp); cr(i,tp); } for (int i = 1;i <= n;i++) { if (!dfn[i]) dfs(i); } printf("%d\n",minn);} |

本文介绍使用Tarjan算法寻找图中大小不为1的最小强连通分量的方法,并提供完整AC代码。通过构建图模型,利用DFS进行遍历,找到符合条件的最小强连通分量。
&spm=1001.2101.3001.5002&articleId=52334976&d=1&t=3&u=6fe8902187c14861af76ea0e5a83fae0)
1万+

被折叠的 条评论
为什么被折叠?



