1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | /// Raihan Ruhin /// CSE, Jahangirnagar University. /// Dhaka-Bangladesh. /// id: raihanruhin (topcoder / codeforces / codechef / uva), 3235 (lightoj) /// mail: raihanruhin@ (yahoo / gmail / facebook) /// blog: ruhinraihan.blogspot.com #include<bits/stdc++.h> using namespace std; #define SET(a) memset(a,-1,sizeof(a)) #define CLR(a) memset(a,0,sizeof(a)) #define PI acos(-1.0) #define MOD 1000000007 #define MX 100010 vector<int>adj[20002]; stack<int>stk; int t, lo[20002], tim[20002], vis[20002], sccrm[20002], scc, done; void tarjan_scc(int u) { t++; vis[u]=1; lo[u]=tim[u]=t; stk.push(u); for(int i=0;i<adj[u].size();i++) { int v = adj[u][i]; if(!vis[v]) { tarjan_scc(v); lo[u]=min(lo[u], lo[v]); } else if(vis[v]==1) lo[u]=min(lo[u], tim[v]); } if(lo[u]==tim[u]) { scc++; do{ done = stk.top(); stk.pop(); sccrm[done]=scc; vis[done]=2; }while(done!=u); } return; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int kk=1, tc, n, m, u, v; string s; cin>>tc; while(tc--) { cin>>n>>m; t=scc=0; while(!stk.empty()) stk.pop(); for(int i=1;i<=n;i++) { adj[i].clear(); vis[i]=0; } while(m--) { cin>>u>>v; adj[u].push_back(v); } for(int i=1;i<=n;i++) if(!vis[i]) tarjan_scc(i); // checking zero indegree and outdegree of scc bool hasIndegree[scc+2], hasOutdegree[scc+2]; CLR(hasIndegree); CLR(hasOutdegree); for(int i=1;i<=n;i++) for(int j=0;j<adj[i].size();j++) if(sccrm[i]!=sccrm[adj[i][j]]) //not in same scc { hasIndegree[sccrm[i]]=true; hasOutdegree[sccrm[adj[i][j]]]=true; } int zeroIndgree=0, zeroOutdegree=0; for(int i=1;i<=scc;i++) { if(!hasIndegree[i]) zeroIndgree++; if(!hasOutdegree[i]) zeroOutdegree++; } if(scc==1) cout<<0<<endl; else cout<<max(zeroIndgree, zeroOutdegree)<<endl; //cout<<"Case "<<kk++<<": "<< <<"\n"; } return 0; } |
Saturday, 3 June 2017
Proving Equivalences (UVa 12167, UVaLive 4287, Regionals 2008 >> Europe - Northwestern)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment