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 to 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 and B are friends, B and C are friends, then A and C are friends.
Input
There are multiple test cases.
For each test case, the first line contains integers n and m (1≤n≤5000,0≤m≤5000) . Then follows m lines, each contains a pair of integers ai,bi (1≤ai,bi≤n) . The pair ai,bi means that the students ai and bi are friend. It is guaranteed that each pair of ai and 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
#include <iostream>
#include <map>
using namespace std;
map<int,int> p;
int par[100005],r[100005],num[100005];
void init(){
for(int i=0;i<100005;i++){
par[i]=i;
num[i]=1;
}
}
int findroot(int x){
if(par[x]==x) return x;
else return par[x]=findroot(par[x]);
}
void unite(int x,int y){
x=findroot(x);
y=findroot(y);
if(x==y){
return;
}
par[y]=x;
num[x]+=num[y];
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
if(m == 0) {
printf("No\n");
continue;
}
p.clear();
init();
int k=1;
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
if(p.find(a)==p.end()){
p[a]=k++;
}
if(p.find(b)==p.end()){
p[b]=k++;
}
unite(p[a],p[b]);
}
for(int i = 1;i<=n;i++){
if(num[findroot(p[i])]%3!=0){
printf("No\n");
break;
}
if(i==n&&num[findroot(p[i])]%3==0){
printf("Yes\n");
}
}
}
}