• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

UVa247 Calling Circles(Floyd warshall算法)

武飞扬头像
kgduu
帮助1

题意

给定两个人相互打电话,如果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;
}

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhihcefj
系列文章
更多 icon
同类精品
更多 icon
继续加载