UVA247 Calling Circles 解题报告-代码

时间:2024-04-11 16:01:44
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define endl '\n';
const int maxn = 30;
const int INF = 0x3fffffff;
const int mod = 1e9 + 7;
map<string, int> IDCache;
vector<string> StrCache;
int G[maxn][maxn];
bool vis[maxn];
int n, m;

int getID(string s) {
    if (IDCache.count(s)) {
        return IDCache[s];
    } else {
        IDCache[s] = StrCache.size();
        StrCache.push_back(s);
        return IDCache[s];
    }
}

void floyd() {
    for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                G[i][j] |= G[i][k] && G[k][j];
}

bool isFirst = true;
void dfs(int u) {
    vis[u] = true;
    if (!isFirst)
        cout << ", ";
    cout << StrCache[u];
    isFirst = false;
    for (int v = 0; v < n; v++) {
        if (v != u && G[u][v] && !vis[v]) {
            dfs(v);
        }
    }
}

void solve() {
    int kase = 0;
    while (cin >> n >> m, n != 0) {
        StrCache.clear();
        IDCache.clear();
        memset(vis, 0, sizeof vis);
        // 输入、建立初始图
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j)
                    G[i][j] = 1;
                else
                    G[i][j] = 0;
            }
        }
        // 将名称字符串映射为整数
        while (m--) {
            string s1, s2;
            cin >> s1 >> s2;
            int u = getID(s1);
            int v = getID(s2);
            G[u][v] = 1;
        }
        // Floyd求传递闭包
        floyd();
        // 求完传递闭包后,只有G[i][j] = G[j][i] = 1时才算一个电话圈,构造一个新图,将在一个电话圈的两个人之间建立一条边,否则为0
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                G[i][j] = G[i][j] && G[j][i];
                G[j][i] = G[i][j];
            }
        }
        // 在新图上输出所有的连通集
        cout << "Calling circles for data set " << ++kase << ":\n";
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                isFirst = true;
                dfs(i);
                cout << endl;
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout.precision(18);

    int Case = 1;
    // cin >> Case;
    while (Case--) {
        solve();
    }  
    return 0;
}