Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
4 3
1 3
3 4
1 4
YES
4 4
3 1
2 3
3 4
1 2
NO
10 4
4 3
5 10
8 9
1 2
YES
3 2
1 2
2 3
NO
题意:给定一个图(盆友关系),判断盆友关系是否合理(若A-B,B-C,则A-C)。
思路:先dfs判断一个盆友圈有圈有c人,若盆友圈合理,那么其中所有点的度都是c-1,再用dfs判断即可。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define N 150005 struct Eage { int v,next; } eage[N*2]; int head[N],cnt[N],cnte; void addEage(int a,int b) { eage[cnte].v=b; eage[cnte].next=head[a]; head[a]=cnte++; cnt[a]++; } bool vis1[N]; int dfs1(int u) { int tmp=1; for(int i=head[u]; i!=0; i=eage[i].next) { int v=eage[i].v; if(vis1[v]==0) { vis1[v]=1; tmp+=dfs1(v); } } return tmp; } bool vis2[N]; bool dfs2(int u,int c) { if(cnt[u]!=c) return 0; for(int i=head[u]; i!=0; i=eage[i].next) { int v=eage[i].v; if(vis2[v]==0) { vis2[v]=1; return dfs2(v,c); } } return 1; } int main() { int n,m; scanf("%d%d",&n,&m); cnte=1; for(int i=1; i<=m; i++) { int a,b; scanf("%d%d",&a,&b); addEage(a,b); addEage(b,a); } int flag=1; for(int i=1;i<=n;i++) { if(vis1[i]==0) { vis1[i]=1; int cc=dfs1(i); if(dfs2(i,cc-1)==0) { flag=0; break; } } } if(flag) printf("YES "); else printf("NO "); return 0; }