Coach
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 (1≤n≤5000,0≤m≤5000) (1≤n≤5000,0≤m≤5000). Then follows m m lines, each contains a pair of integers ai,bi ai,bi (1≤ai,bi≤n) (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;
}
}