NOIP2015 信息传递 解题报告(强连通分量)

本文介绍使用Tarjan算法寻找图中大小不为1的最小强连通分量的方法,并提供完整AC代码。通过构建图模型,利用DFS进行遍历,找到符合条件的最小强连通分量。

在线评测:

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值