UVA 11504 Dominos 强连通分量
找出强连通分量,缩点后统计入度为0的结点数。
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; #define pb(a) push(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) { return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) { return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #else freopen("d:\\in1.txt","r",stdin); freopen("d:\\out1.txt","w",stdout); #endif } int getch() { int ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } const int maxn=111222; int pre[maxn],lowlink[maxn],sccno[maxn],scc_cnt,dfs_clock; int deg[maxn]; vector<int> g[maxn]; stack<int> s; void dfs(int u) { lowlink[u]=pre[u]=++dfs_clock; s.push(u); for(int i=0;i<g[u].size();i++) { int v=g[u][i]; if(!pre[v]) { dfs(v); lowlink[u]=min(lowlink[u],lowlink[v]); }else if(!sccno[v]) lowlink[u]=min(lowlink[u],lowlink[v]); } if(lowlink[u]==pre[u]) { scc_cnt++; while(1) { int x=s.top();s.pop(); sccno[x]=scc_cnt; if(x==u)break; } } } void find_scc(int n) { memset(pre,0,sizeof(pre)); memset(sccno,0,sizeof(sccno)); dfs_clock=scc_cnt=0; for(int i=1;i<=n;i++) if(!pre[i])dfs(i); } int main() { int t; scanf("%d",&t); for(int ca=1;ca<=t;ca++) { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) g[i].clear(); for(int i=1;i<=m;i++) { int u,v; scanf("%d%d",&u,&v); g[u].push_back(v); } find_scc(n); memset(deg,0,sizeof(deg)); for(int i=1;i<=n;i++) { for(int j=0;j<g[i].size();j++) { int u=i,v=g[i][j]; if(sccno[u]!=sccno[v]) deg[sccno[v]]=1; } } int num=0; for(int i=1;i<=scc_cnt;i++) if(!deg[i])num++; printf("%d\n",num); } return 0; }