首页 > 代码库 > CF:Problem 427C - Checkposts强连通 Tarjan算法

CF:Problem 427C - Checkposts强连通 Tarjan算法

tarjan算法第一题   

喷我一脸。。。。把手写栈的类型开成了BOOL,一直在找错。。。


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define maxn 100005

const int MOD=1000000007;

using namespace std;

struct node
{
    int to,next;
}edge[maxn*3];

int dfn[maxn],low[maxn],head[maxn],a[maxn],s[maxn];
bool instack[maxn];
int cnt,n,m,c,top;
long long ans1,ans2;

void add(int x,int y)
{
    edge[cnt].to = y;
    edge[cnt].next = head[x];
    head[x]=cnt++;
}

void tarjan(int x)
{
    dfn[x]=low[x]=++c;
    instack[x] = true;
    s[++top]=x;

    for(int i=head[x];i!=-1;i=edge[i].next)
    {
        int tmp = edge[i].to;
        if(!dfn[tmp])
        {
            tarjan(tmp);
            if(low[x]>low[tmp])
                low[x] = low[tmp];
        }
        else if(instack[tmp])
        {
            if(low[x]>dfn[tmp])
                low[x] = dfn[tmp];
        }
    }
    if(low[x]==dfn[x])
    {
        int t;
        int minx = MOD,sum = 0;
        do{
            t = s[top--];
            instack[t] = false;
            if(a[t]<minx)
            {
                minx = a[t];
                sum = 1;
            }
            else if(a[t] == minx)
                sum++;
        }while(t!=x);
        ans1+=minx;
        ans2=(ans2*sum)%MOD;
    }
}

int main()
{
    int p,b;
    while(scanf("%d",&n)!=EOF)
    {
        cnt = 0;
        memset(head,-1,sizeof(head));
        memset(instack,0,sizeof(instack));
        memset(dfn,0,sizeof(dfn));
        memset(low,0,sizeof(low));
        memset(s,0,sizeof(s));

        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d",&p,&b);
            add(p,b);
        }
        c = 0,top = 0,ans1 = 0,ans2 = 1;
        for(int k=1;k<=n;k++)
        {
            if(!dfn[k])
                tarjan(k);
        }

        printf("%I64d %I64d\n",ans1,ans2);
    }
    return 0;
}