2017年上海金马五校程序设计竞赛(网上资格赛) B Coach(并查集)

Coach


 

Time Limit: 1 s

Description

In the ACM training team, the coach wants to split all students into many groups and each group consists of three students. Let's assume that all students are numbered from  1 1 to  n n. The teacher wants the groups to achieve good results, so he wants to hold the following condition: In a group of three students, they are friends. Also it is obvious that each student must be in exactly one team. If  A A and  B B are friends,  B B and  C C are friends, then  A A and  C C are friends.

 

Input

There are multiple test cases.

For each test case, the first line contains integers  n n and  m m  (1n5000,0m5000) (1≤n≤5000,0≤m≤5000). Then follows  m m lines, each contains a pair of integers  ai,bi ai,bi  (1ai,bin) (1≤ai,bi≤n). The pair  ai,bi ai,bi means that the students  ai ai and  bi bi are friend. It is guaranteed that each pair of  ai ai and  bi bi occurs in the input at most once.

 

Output

If the required group division plan doesn't exist, print “No”. Otherwise, print “Yes”.

 

Sample Input

3 0
6 4
1 2
2 3
4 5
5 6

 

Sample Output

No
Yes

 


Author: betty

并查集的应用

题目链接:点击打开链接

题目是说:让你判断一下能否让三个朋友一队。

我的代码:

#include<iostream>
#include<math.h>
#include<map>
#include<memory.h>
using namespace std;
int a[5005];
int find(int t)
{
    if(t!=a[t])
        a[t]=find(a[t]);
    return a[t];
}
int main()
{
    int n,m;
    while(cin>>n>>m)
    {

        int x,y;
        for(int i=1; i<=n; i++) //并查集初始化
            a[i]=i;
        for(int i=0; i<m; i++)
        {
            cin>>x>>y;
            x=find(x);//找x的祖先
            y=find(y);//找y的祖先
            if(x!=y)//x和y的祖先不相同增加一条关系
            {
                a[y]=x;
            }
        }
        map<int,int>q;
        map<int,int>::iterator it;
        for(int i=1;i<=n;i++)
        {
            int temp;
            temp=find(i);//i的祖先
            q[temp]++;
        }
        int flag=1;
        for(it=q.begin();it!=q.end();it++)
        {
            if(it->second%3!=0)
                flag=0;
        }
        if(flag==0||n%3!=0)
            cout<<"No"<<endl;
        else
            cout<<"Yes"<<endl;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值