poj1236 Network of Schools(tarjan缩点)

来源:互联网 发布:软件测试表情包 编辑:程序博客网 时间:2024/06/05 17:55

强连通缩点重构图,入度为0的点的个数即为第一问的答案,第二问的答案为入度为0的点的个数和出度为0的点的个数的最大值。证明见百度。

#include <cstdio>#include <cstring>#include <algorithm>#include <stack>using namespace std;#define ll long long#define inf 0x3f3f3f3f#define N 110#define pa pair<int,int>inline int read(){    int x=0,f=1;char ch=getchar();    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();    return x*f;}int n,dfn[N],low[N],dfnum=0,bel[N],scc=0,in[N],out[N];bool inq[N],mp[N][N],mp1[N][N];stack<int>qq;void tarjan(int x){    dfn[x]=low[x]=++dfnum;qq.push(x);inq[x]=1;    for(int y=1;y<=n;++y){        if(!mp[x][y]) continue;        if(!dfn[y]) tarjan(y),low[x]=min(low[x],low[y]);        else if(inq[y]) low[x]=min(low[x],dfn[y]);    }    if(dfn[x]==low[x]){        ++scc;while(1){            int y=qq.top();qq.pop();inq[y]=0;            bel[y]=scc;if(y==x) break;        }    }}void rebuild(){    for(int x=1;x<=n;++x)        for(int y=1;y<=n;++y){            if(!mp[x][y]) continue;            if(bel[x]!=bel[y]&&!mp1[bel[x]][bel[y]])                mp1[bel[x]][bel[y]]=1,in[bel[y]]++,out[bel[x]]++;        }}int main(){//  freopen("a.in","r",stdin);    n=read();    for(int i=1;i<=n;++i){        while(1){            int x=read();if(!x) break;mp[i][x]=1;        }    }    for(int i=1;i<=n;++i) if(!dfn[i]) tarjan(i);    rebuild();int ans1=0,ans2=0;//ans1---入度为0的个数,ans2---出度为0的个数     for(int i=1;i<=scc;++i){        if(in[i]==0) ans1++;        if(out[i]==0) ans2++;    }    if(scc==1){puts("1");puts("0");return 0;}    printf("%d\n%d\n",ans1,max(ans1,ans2));    return 0;}
阅读全文
0 0
原创粉丝点击