從某一點開始,以層次遍歷的方式建樹
若三點a、b、c互相連接,首先必先經過其中一點a,然后a可以拓展b、c兩點,b、c兩點的高度是相同的,若b(c)拓展時找到高度與之相同的點,則存在三點互相連接
//等等:該算法正確證有待斟酌,我在看到這個方法的增強版,這方法也許有漏洞
//(注:這想法應該是在17年網絡同步賽的時候別人想到的(大致是這樣),但貌似寫的方法跟我不同)
與acm網絡同步賽的某道題有點類似(還有那個定理:若人數大於等於六個,至少存在三個人互相認識,或三個人互不認識)
別人的方法在這(https://www.jisuanke.com/minicourse/1249):
1 /* 2 從某一點開始,以層次遍歷的方式建樹 3 若三點a、b、c互相連接,首先必先經過其中一點a,然后a可以拓展b、c兩點,b、c兩點的高度是相同的,若b(c)拓展時找到高度與之相同的點,則存在三點互相連接 4 */ 5 #include <cstdio> 6 #include <cstdlib> 7 #include <cstring> 8 #include <cmath> 9 #include <list> 10 #include <stack> 11 #include <vector> 12 #include <set> 13 #include <map> 14 #include <queue> 15 #include <algorithm> 16 #include <iostream> 17 using namespace std; 18 19 struct node 20 { 21 long d; 22 struct node *next; 23 }*point[100005],*p; 24 long q[100005],dep[100005]; 25 26 int main() 27 { 28 long n,m,i,head,tail,a,b; 29 scanf("%ld%ld",&n,&m); 30 for (i=1;i<=n;i++) 31 point[i]=NULL; 32 for (i=1;i<=m;i++) 33 { 34 scanf("%ld%ld",&a,&b); 35 p=(struct node *) malloc (sizeof(struct node)); 36 p->d=a; 37 p->next=point[b]; 38 point[b]=p; 39 40 p=(struct node *) malloc (sizeof(struct node)); 41 p->d=b; 42 p->next=point[a]; 43 point[a]=p; 44 } 45 for (i=1;i<=n;i++) 46 dep[i]=-1; 47 //有可能有很多塊 48 for (i=1;i<=n;i++) 49 if (dep[i]==-1) 50 { 51 q[1]=i; dep[i]=0; 52 head=0; 53 tail=1; 54 while (head<tail) 55 { 56 head++; 57 p=point[q[head]]; 58 while (p) 59 { 60 if (dep[p->d]==-1) 61 { 62 tail++; 63 q[tail]=p->d; 64 dep[p->d]=dep[q[head]]+1; 65 } 66 else if (dep[p->d]==dep[q[head]]) 67 { 68 printf("1"); 69 return 0; 70 } 71 p=p->next; 72 } 73 } 74 } 75 printf("0"); 76 return 0; 77 }