首页 > 学院 > 开发设计 > 正文

HDU1213 How Many Tables

2019-11-08 00:57:01
字体:
来源:转载
供稿:网友

问题链接:HDU1213 How Many Tables。

问题简述:测试用例有T组。输入n和m,分别表示总人数和朋友对的数量。再输入m个数对s和d表示s和d是朋友。朋友以及间接朋友坐在同一张桌子上。计算需要几张桌子?

问题分析:这是一个有关图的连通性问题,可以用并查集来解决。并查集中,连通的各个结点都会指向相同的根。

程序说明:程序中,构建一个用并查集,使得相互连通的子图指向相同的根,最后数一下有几个相互连通的子图就可以了。

AC的C++语言程序如下:

/* HDU1213 How Many Tables */#include <iostream>#include <vector>using namespace std;// 并查集类class UF {PRivate:    vector<int> v;public:    UF(int n) {        for(int i=0; i<=n; i++)            v.push_back(i);    }    int Find(int x) {        for(;;) {            if(v[x] != x)                x = v[x];            else                return x;        }    }    bool Union(int x, int y) {        x = Find(x);        y = Find(y);        if(x == y)            return false;        else {            v[x] = y;            return true;        }    }};int main(){    int t, n, m, src, dest, count;    // 输入测试用例数量    cin >> t;    while(t--) {        cin >> n >> m;        UF uf(n);        // 输入m个朋友关系,构建并查集        while(m--) {            cin >> src >> dest;            if(uf.Find(src) != uf.Find(dest))                uf.Union(src, dest);        }        // 计算需要桌子的数量:即相互联通子图的数量        count = 0;        for(int i=1; i<=n; i++)            if(uf.Find(i) == i)                count++;        // 输出结果        cout << count << endl;    }    return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表