这题目实在是很让人无语,FJ真是一个清新可爱的男孩子。。
比赛完了查题解才发现是给定一个有向图,求强连通分量。
#include <iostream> #include <cstdio> #include <cstring> #include <vector> using namespace std; vector<int> g[10010]; int dfn[10010],low[10010],tag; int stack[10010],s_top; bool instack[10010]; int min(int a,int b) { return a>b?b:a; } int tarjan(int u) { int i,v,t; dfn[u]=tag; low[u]=tag; tag++; stack[s_top]=u; s_top++; instack[u]=true; for (i=0; i<g[u].size(); i++) { v=g[u][i]; if (dfn[v] == -1) { tarjan(v); low[u]=min(low[u],low[v]); } else if (dfn[v] != -1 && instack[v] == true) { low[u]=min(low[u],dfn[v]); } } t=0; if (dfn[u] == low[u]) { while (u != stack[s_top-1]) { t++; instack[stack[s_top-1]]=false; s_top--; } t++; instack[stack[s_top-1]]=false; s_top--; } return t; } int main() { int n,m,t1,t2,i,j,cnt,ans; scanf("%d%d",&n,&m); for (i=1; i<=n; i++) { g[i].clear(); } for (i=0; i<m; i++) { scanf("%d%d",&t1,&t2); g[t1].push_back(t2); } memset(dfn,-1,sizeof(dfn)); memset(instack,false,sizeof(instack)); ans=0; tag=1; s_top=0; for (i=1; i<=n; i++) { if (dfn[i] == -1) { cnt=tarjan(i); if (cnt >= 2) ans++; } } printf("%d\n",ans); }
#include <iostream> #include <vector> #include <cstdio> #include <cstring> using namespace std; vector<int> g[10010],gt[10010]; int f[10010],order[10010]; bool v[10010]; int ans,lf; void DFS_OriginGraph(int cur) { int i; for (i=0; i<g[cur].size(); i++) { if (!v[g[cur][i]]) { v[g[cur][i]]=true; DFS_OriginGraph(g[cur][i]); } } f[lf]=cur; lf++; } void DFS_TransGraph(int cur) { int i; for (i=0; i<gt[cur].size(); i++) { if (!v[gt[cur][i]]) { v[gt[cur][i]]=true; DFS_TransGraph(gt[cur][i]); } } f[ans]=cur; ans++; } int main() { int n,m,t1,t2,i,j,cnt; scanf("%d%d",&n,&m); for (i=1; i<=n; i++) { g[i].clear(); gt[i].clear(); } for (i=0; i<m; i++) { scanf("%d%d",&t1,&t2); g[t1].push_back(t2); gt[t2].push_back(t1); } memset(v,false,sizeof(v)); cnt=0; lf=0; for (i=1; i<=n; i++) { if (!v[i]) { v[i]=true; DFS_OriginGraph(i); } } memset(v,false,sizeof(v)); memcpy(order,f,sizeof(f)); for (i=lf-1; i>=0; i--) { if (!v[order[i]]) { ans=0; v[order[i]]=true; DFS_TransGraph(order[i]); if (ans >= 2) cnt++; } } printf("%d\n",cnt); }