Popular Cows(tarjan + 缩点)

匿名 (未验证) 提交于 2019-12-03 00:30:01
Language:Default
Popular Cows
Time Limit:Memory Limit:
Total Submissions:Accepted:

Description



Input




Output


Sample Input

3 3 1 2 2 1 2 3 

Sample Output

1

【题意】:

tarjia算法了解一下

https://www.byvoid.com/zhs/blog/scc-tarjan

https://blog.csdn.net/qq_34374664/article/details/77488976

AC代码:

#include<cstdio> #include<iostream> #include<cstring> #include<stack> #include<cmath>  using namespace std; const int maxn=1e4+50; const int maxm=5e4+50;  int head[maxn],LOW[maxn],DFN[maxn],id[maxn],cnt[maxn]; bool mark[maxn]; int N,M,time=0,scc=0; stack<int>sta;  struct edge_t{     int to,next; }edge[maxm];  void init() {     memset(head,-1,sizeof(head));     memset(DFN,0,sizeof(DFN));     memset(id,0,sizeof(id));     memset(cnt,0,sizeof(cnt));     memset(LOW,0,sizeof(LOW));     memset(mark,false,sizeof(mark)); }  void tarjan( int u ) {     DFN[u]=LOW[u]=++time;     sta.push(u);     mark[u]=true;     for( int k=head[u]; k!=-1; k=edge[k].next )     {         int v=edge[k].to;         if(!DFN[v])         {             tarjan(v);             LOW[u]=min( LOW[u],LOW[v] );         }         else if(mark[v])         {             LOW[u]=min(LOW[u],DFN[v]);         }     }     if(DFN[u]==LOW[u])     {         scc++;         int v;         do         {             v=sta.top();             sta.pop();             id[v]=scc;             mark[v]=false;             cnt[scc]++;         }         while(u!=v);     } }  void solve() {     for( int i=1; i<=N; i++ )  if(!DFN[i])  tarjan(i);      memset(mark,0,sizeof mark);     for( int i=1; i<=N; i++ )     {         for( int k=head[i]; k!=-1; k=edge[k].next )         {             if(id[i]!=id[edge[k].to])                 mark[id[i]]=true;         }     }     int pos=0,lab=0;     for( int i=1; i<=scc; i++ )if(!mark[i])     {         lab++;         pos=i;     }     if(lab>1)printf("0\n");     else printf("%d\n",cnt[pos]); }  int main() {     init();     scanf("%d%d",&N,&M);     for( int i=0; i<M; i++ )     {         int a,b;         scanf("%d%d",&a,&b);         edge[i].to=b;         edge[i].next=head[a];         head[a]=i;     }     solve();      return 0;  } 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!