https://vjudge.net/problem/UVA-247
题意:
如果两个人相互打电话,则说他们在同一个电话圈里。例如,a打给b,b打给c,c打给d,d打给a,则这4个人在同一个圈里;如果e打给f但f不打给e,则不能推出e和f在同一个电话圈里,输出所有电话圈。
思路:
通过Floyd求一个传递闭包。最后dfs输出每一个电话圈即可。
传递闭包的求法:
for (int k = ; k < n;k++)
for (int i = ; i < n;i++)
for (int j = ; j < n; j++)
d[i][j] = d[i][j] || (d[i][k] && d[k][j]);
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<vector>
using namespace std; int n, m;
int d[][];
string s1, s2;
map<string, int> ID;
vector<string> name;
int vis[]; void dfs(int k)
{
vis[k] = ;
for (int i = ; i < n; i++)
{
if (d[k][i] && d[i][k])
{
if (!vis[i])
{
cout << ", " << name[i];
dfs(i);
}
}
}
} int main()
{
//freopen("D:\\txt.txt", "r", stdin);
int kase = ;
while (scanf("%d%d", &n, &m))
{
if (n == && m == ) break;
if (kase > ) printf("\n");
memset(d, , sizeof(d));
memset(vis, , sizeof(vis));
ID.clear();
name.clear();
int cnt = ;
for (int i = ; i < m; i++)
{
cin >> s1 >> s2;
if (!ID.count(s1))
{
ID[s1] = cnt++;
name.push_back(s1);
}
if (!ID.count(s2))
{
ID[s2] = cnt++;
name.push_back(s2);
}
int x = ID[s1];
int y = ID[s2];
d[x][y] = ;
} for (int k = ; k < n;k++)
for (int i = ; i < n;i++)
for (int j = ; j < n; j++)
d[i][j] = d[i][j] || (d[i][k] && d[k][j]); printf("Calling circles for data set %d:\n", kase++);
for (int i = ; i < n; i++)
{
if (!vis[i])
{
cout << name[i];
dfs(i);
printf("\n");
}
}
}
return ;
}