标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5742 Accepted Submission(s): 1973
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<vector> 5 #include<cstring> 6 using namespace std; 7 const int mxn=48000; 8 int top,stack[mxn]; 9 bool inst[mxn]; 10 int cnt,dnow; 11 int dfn[mxn],low[mxn]; 12 int belone[mxn],in[mxn],out[mxn]; 13 vector<int> e[mxn]; 14 void clear(){ 15 cnt=0;dnow=0;top=0; 16 memset(dfn,-1,sizeof(dfn)); 17 memset(inst,false,sizeof(inst)); 18 memset(in,0,sizeof in); 19 memset(out,0,sizeof out); 20 for(int i=1;i<mxn;i++) e[i].clear(); 21 } 22 int n,m; 23 void tarjan(int s){ 24 int v=0,i; 25 dfn[s]=++dnow; 26 low[s]=dfn[s]; 27 inst[s]=true; 28 stack[++top]=s; 29 int si=e[s].size(); 30 for(i=0;i<si;i++){ 31 v=e[s][i]; 32 if(dfn[v]==-1){ 33 tarjan(v); 34 low[s]=min(low[v],low[s]); 35 } 36 else if(inst[v]){ 37 low[s]=min(dfn[v],low[s]); 38 } 39 } 40 if(dfn[s]==low[s]){ 41 cnt++; 42 do{ 43 v=stack[top--]; 44 belone[v]=cnt; 45 inst[v]=false; 46 }while(s!=v); 47 } 48 return; 49 } 50 void calc(){ 51 if(cnt==1){ 52 printf("0\n");return; 53 } 54 int i,j; 55 for(i=1;i<=n;i++){ 56 for(j=0;j<e[i].size();j++){ 57 int v=e[i][j]; 58 if(belone[i]!=belone[v]){ 59 in[belone[v]]++; 60 out[belone[i]]++; 61 } 62 } 63 } 64 int idg=0,odg=0; 65 for(i=1;i<=cnt;i++){ 66 if(!in[i])idg++; 67 if(!out[i])odg++; 68 } 69 printf("%d\n",max(idg,odg)); 70 return; 71 } 72 int main(){ 73 int T; 74 scanf("%d",&T); 75 while(T--){ 76 scanf("%d%d",&n,&m); 77 if(!m){ 78 if(n==1)printf("0\n"); 79 else printf("%d\n",n); 80 continue; 81 } 82 clear(); 83 int i,j; 84 int u,v; 85 for(i=1;i<=m;i++){ 86 scanf("%d%d",&u,&v); 87 e[u].push_back(v); 88 } 89 for(i=1;i<=n;i++){ 90 if(dfn[i]==-1)tarjan(i); 91 } 92 calc(); 93 } 94 return 0; 95 }
标签:
原文地址:http://www.cnblogs.com/SilverNebula/p/5744665.html