寒假10.7

Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2
5 3
1 2
2 3
4 5

5 1
2 5
Sample Output
2
4

本题运用动态规划,如遇到认识者及使其于上一认识者相等,最后查找有多少个不相同者,即可知道有多少人不同桌。

#include<iostream>
using namespace std;
int p[1005];
int find(int x)
{
    if (x != p[x])
        p[x] = find(p[x]);
    return p[x];
}
int h(int x, int y)
{
    return  p[x] = y;
}
int main()
{
    int t, i, a, b;
    cin >> t;
    while (t--)
    {
        int n, m, x = 0;
        cin >> n >> m;
        for (i = 1; i <= n; i++)
            p[i] = i;
        for (i = 1; i <= m; i++)
        {
            cin >> a >> b;
            a = find(a);
            b = find(b);
            if (a != b)
                h(a, b);
        }
        for (i = 1; i <= n; i++)
        {
            if (p[i] == i)
                x++;
        }
        cout << x;
        if (t != 0)
        {
            cout << endl;
        }
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 关于诊断X线机准直器的作用,错误的是()。 (6.0 分) A. 显示照射野 B. 显示中心线 C. 屏蔽多...
    我们村我最帅阅读 13,733评论 0 5
  • 1. 下列叙述错误的是()。 (2.0 分) A. 质量管理包括QA和QC一切活动的全部过程 B. 影像质量是指对...
    我们村我最帅阅读 9,639评论 0 8
  • 20天的生活,用一个字来形容就是“找”。找目标,找定位,找依托,找让自己赖以生存的资 本。 有些事不必拿...
    水中绽放阅读 2,540评论 0 1
  • 第一次用指甲油画画,没有参照对象,没有章法,全凭个人感觉,于是构图和色彩都不对,可是自己却喜欢,没有中规中矩,只有...
    沧海之杋阅读 3,304评论 0 3
  • Methods ①:position 兼容性:IE6不支持解决方案:http://nec.netease.com/...
    夜月孤鸿阅读 3,868评论 0 0