UVA - 247 Calling Circles
#include<bits/stdc++.h> #define _for(i,a,b) for(int i=a;i<b;i++) using namespace std; const int maxn = 25 + 3; int g[maxn][maxn]; int gg[maxn][maxn]; int g2[maxn][maxn]; int n, m; map<string, int>id; map<int,string>name; int getID(string &s) { if(id.count(s)) return id[s]; id[s] = id.size() - 1; name[id[s]] = s; return id[s]; } void floyd() { _for(k,0,n) _for(i,0,n) _for(j,0,n) g[i][j] = g[i][j] ? 1: (g[i][k] && g[k][j]); } int vis[maxn]; vector<int>ans; void solve(int s) { vis[s] = 1; ans.push_back(s); _for(i,0,n){ if(g2[s][i] && !vis[i]){ solve(i); } } } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int kase = 0; while(cin >> n >> m && n){ id.clear(); name.clear(); memset(g, 0, sizeof(g)); memset(g2, 0, sizeof(g2)); _for(i,0,n){ g[i][i] = 1; } _for(i,0,m){ string s1, s2; cin >> s1 >> s2; int id1 = getID(s1); int id2 = getID(s2); g[id1][id2] = 1; } memcpy(gg, g, sizeof(gg)); floyd(); _for(i,0,n){ _for(j,0,n){ if(g[i][j] && g[j][i]){ g2[i][j] = g2[j][i] = 1; } } } memset(vis, 0, sizeof(vis)); if(kase != 0){ cout << endl; } printf("Calling circles for data set %d:\n", ++kase); //if(m != 0) //如果没有边,不应该输出各个点 _for(i,0,n){ ans.clear(); if(!vis[i]){ solve(i); //如果点没在电话记录里出现过,不应该自成一个圈。或者也可以在下面输出name的时候处理,先判断是否有名字 int u = ans[0]; int ok = (ans.size() == 1)? 0 : 1; if(ans.size() == 1) _for(i,0,n){ if(i != u) if(gg[u][i] || gg[i][u]){ ok = 1; break; } } if(ok) _for(i,0,ans.size()){ if(i == ans.size() - 1) cout << name[ans[i]] << endl; else cout << name[ans[i]] << ", "; } } } } return 0; }