思路:用Floyd求传递闭包。
附:逗号后的空格没看到,WA了好多次……。还有就是强连通分量也可以做,但是对这个题来说太麻烦,而且不方便输出,。
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<map> using namespace std; int n,m; map<string,int> ma; map<int,string> mb; int maps[50][50],vis[50]; void dfs(int u) { vis[u] = 1; for(int i = 1;i <= n;i++) { if(!vis[i] && maps[u][i] && maps[i][u]) { cout<<", "<<mb[i]; dfs(i); } } return ; } int main() { string a,b; int tot,u,v,ca = 0 ; while(~scanf("%d%d",&n,&m)) { if(n+m == 0) break; ma.clear(); mb.clear(); memset(maps,0,sizeof(maps)); tot = 1; for(int i = 1;i <= m;i++) { cin>>a>>b; if(!ma[a]) ma[a] = tot++; if(!ma[b]) ma[b] = tot++; u = ma[a]; v = ma[b]; mb[u] = a; mb[v] = b; maps[u][v] = 1; } for(int k = 1;k <= n;k++) { for(int i = 1;i <= n;i++) { for(int j = 1;j <= n;j++) { maps[i][j] = maps[i][j] || (maps[i][k]&&maps[k][j]); } } } memset(vis,0,sizeof(vis)); if(!ca) puts(""); printf("Calling circles for data set %d: ",++ca); for(int i = 1;i <= n;i++) { if(!vis[i]) { cout<<mb[i]; dfs(i); cout<<endl; } } } }