POJ 1236 Network of Schools
强连通分量求入度为零和出度为零的个数;
1 #include<iostream> 2 #include<algorithm> 3 #include<stdio.h> 4 #include<stdlib.h> 5 #include<string.h> 6 #define maxn 110 7 using namespace std; 8 int head1[maxn],head2[maxn]; 9 int out[maxn],in[maxn]; 10 int mark1[maxn],mark2[maxn]; 11 int Et[maxn],vis[maxn],ss[maxn]; 12 int cont1,cont2,p,q,n,ans,t,k,num; 13 struct node 14 { 15 int to,next; 16 } E1[maxn*maxn],E2[maxn*maxn],e[maxn*maxn]; 17 void Init() 18 { 19 memset(head1,-1,sizeof(head1)); 20 memset(head2,-1,sizeof(head2)); 21 memset(out,0,sizeof(out)); 22 memset(in,0,sizeof(in)); 23 memset(mark1,0,sizeof(mark1)); 24 memset(mark2,0,sizeof(mark2)); 25 memset(Et,0,sizeof(Et)); 26 memset(vis,0,sizeof(vis)); 27 memset(ss,0,sizeof(ss)); 28 p=q=cont1=cont2=k=t=1; 29 }; 30 void add(int a,int b) 31 { 32 E1[p].to=b,E1[p].next=head1[a],head1[a]=p++; 33 E2[q].to=a,E2[q].next=head2[b],head2[b]=q++; 34 } 35 void DFS1(int u) 36 { 37 mark1[u]=1; 38 for(int i=head1[u]; i!=-1; i=E1[i].next) 39 if(!mark1[E1[i].to]) 40 DFS1(E1[i].to); 41 Et[cont1++]=u; 42 } 43 void DFS2(int u) 44 { 45 mark2[u]=1; 46 num++; 47 vis[u]=cont2; 48 for(int i=head2[u]; i!=-1; i=E2[i].next) 49 { 50 if(!mark2[E2[i].to]) 51 DFS2(E2[i].to); 52 } 53 } 54 int main() 55 { 56 int i,b; 57 while(~scanf("%d",&n)) 58 { 59 Init(); 60 for(i=1; i<=n; i++) 61 { 62 while(scanf("%d",&b),b) 63 { 64 add(i,b); 65 e[k].to=i,e[k].next=b; 66 k++; 67 } 68 } 69 for(i=1; i<=n; i++) 70 if(!mark1[i]) 71 DFS1(i); 72 for(i=cont1-1; i>=1; i--) 73 { 74 if(!vis[Et[i]]) 75 { 76 num=0; 77 DFS2(Et[i]); 78 ss[cont2++]=num; 79 } 80 } 81 for(i=1; i<=k; i++) 82 { 83 if(vis[e[i].to] != vis[e[i].next]) 84 { 85 out[vis[e[i].to]]++; 86 in[vis[e[i].next]]++; 87 } 88 } 89 int sum; 90 sum = num =0; 91 for(i=1; i<cont2; i++) 92 { 93 if(!out[i]) 94 sum++; 95 if(!in[i]) 96 num++; 97 } 98 if(cont2==2) 99 printf("1\n0\n"); 100 else 101 { 102 printf("%d\n",num); 103 printf("%d\n",max(sum,num)); 104 } 105 } 106 return 0; 107 }