UVa247 Calling Circles(Floyd warshall算法)

题意

给定两个人相互打电话,如果a打给b,b打给c,c打给a,则说a,b,c在同一电话圈中。给出n个人的m次通话,输出所有的电话圈

思路

用graphuv=1表示u和v之间有打电话。在使用floyd算法计算所有的点对之间的值。graphuv=1表示u,v之间有直接或者间接打电话。如果graphuv = 1并且graphvu=1,说明u和v是在同一个电话圈

代码如下

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

const int N = 30;

#define _for(i, a, b) for(int i = (a); i < (b); i++)
#define _rep(i, a, b) for (int i = (a); i <= (b); i++)

int n, m;
int graph[N][N];
bool vis[N];
map<string, int> nameMap;
vector<string> names;


int getId(const string& name)
{
    if (!nameMap.count(name))
    {
        int size = names.size();
        nameMap[name] = size;
        names.push_back(name);
    }


    return nameMap[name];
}

void fastio()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
}

int main()
{
    fastio();

    #ifndef ONLINE_JUDGE
        ifstream fin("f:\\OJ\\uva_in.txt");
        streambuf* back = cin.rdbuf(fin.rdbuf());
    #endif

    int kase = 1;
    while (cin >> n >> m) {
        if (n == 0 && m == 0) {
            break;
        }

        if (kase > 1) {
            cout << endl;
        }

        nameMap.clear();
        names.clear();
        memset(graph, 0, sizeof(graph));
        fill(vis, vis + N, false);
        _for(i, 0, m) {
            string a, b;
            cin >> a >> b;
            int u = getId(a);
            int v = getId(b);
            graph[u][v] = 1;
        }

        _for(k, 0, n) {
            _for(i, 0, n) {
                _for(j, 0, n) {
                    graph[i][j] = graph[i][j] || (graph[i][k] && graph[k][j]);
                }
            }
        }

        cout << "Calling circles for data set " << kase << ":" << endl;
        _for(u, 0, n) {
            if (vis[u]) {
                continue;
            }

            vis[u] = true;
            cout << names[u];

            _for(v, 0, n) {
                if (!vis[v] && graph[u][v] && graph[v][u]) {
                    vis[v] = true;
                    cout << ", " << names[v];
                }
            }

            cout << endl;
        }

        kase++;
    }


    #ifndef ONLINE_JUDGE
        cin.rdbuf(back);
    #endif

    return 0;
}
相关推荐
武子康5 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw0511 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术12 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs13 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575914 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI1 天前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi1 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M1 天前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法