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

来源:互联网 发布:世界历史书 知乎 编辑:程序博客网 时间:2024/05/29 17:19

Coach


From: DHUOJ, 2016060703
 

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 11 to nn. 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 AA and BB are friends, BB and CC are friends, then AA and CC are friends.

 

Input

There are multiple test cases.

For each test case, the first line contains integers nn and mm (1n5000,0m5000)(1≤n≤5000,0≤m≤5000). Then follows mm lines, each contains a pair of integers ai,biai,bi (1ai,bin)(1≤ai,bi≤n). The pair ai,biai,bi means that the students aiai and bibi are friend. It is guaranteed that each pair of aiai and bibi 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 06 41 22 34 55 6

 

Sample Output

NoYes

 


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



阅读全文
0 0
原创粉丝点击