UVa247 Calling Circles(Floyd warshall算法)

题意

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

思路

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

代码如下

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值