尤拉路知識點整理
阿新 • • 發佈:2018-11-30
題解報告:hdu 1878 歐拉回路
Problem Description
歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且可以回到起點的一條迴路。現給定一個圖,問是否存在歐拉回路?Input
測試輸入包含若干測試用例。每個測試用例的第1行給出兩個正整數,分別是節點數N ( 1 < N < 1000 )和邊數M;隨後的M行對應M條邊,每行給出一對正整數,分別是該條邊直接連通的兩個節點的編號(節點從1到N編號)。當N為0時輸入結束。
Output
每個測試用例的輸出佔一行,若歐拉回路存在則輸出1,否則輸出0。Sample Input
3 3 1 2 1 3 2 3 3 2 1 2 2 3 0Sample Output
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int maxn=1005; 5 int T,n,m,deg[maxn],fa[maxn],a,b,f1,f2; 6 void init(){ 7 for(int i=1;i<=n;++i)fa[i]=i; 8 } 9 int findt(int x){ 10 intper=x,tmp; 11 while(fa[per]!=per)per=fa[per]; 12 while(x!=per){tmp=fa[x];fa[x]=per;x=tmp;} 13 return x; 14 } 15 void unite(int x,int y){ 16 x=findt(x),y=findt(y); 17 if(x!=y)fa[x]=y; 18 } 19 int main(){ 20 while(cin>>n&&n){ 21 cin>>m; 22memset(deg,0,sizeof(deg));init();f1=f2=0; 23 while(m--){ 24 cin>>a>>b; 25 deg[a]++,deg[b]++; 26 unite(a,b); 27 } 28 for(int i=1;i<=n;++i) 29 f1+=(i==fa[i]?1:0),f2+=(deg[i]&1?0:1); 30 if(f1==1&&f2==n)puts("1");///歐拉回路 31 else puts("0"); 32 33 } 34 return 0; 35 }
題解報告:NYOJ 42 一筆畫問題
Problem Description
zyc從小就比較喜歡玩一些小遊戲,其中就包括畫一筆畫,他想請你幫他寫一個程式,判斷一個圖是否能夠用一筆畫下來。規定,所有的邊都只能畫一次,不能重複畫。
Input
第一行只有一個正整數N(N<=10)表示測試資料的組數。
每組測試資料的第一行有兩個正整數P,Q(P<=1000,Q<=2000),分別表示這個畫中有多少個頂點和多少條連線。(點的編號從1到P)
隨後的Q行,每行有兩個正整數A,B(0<A,B<P),表示編號為A和B的兩點之間有連線。
Output
如果存在符合條件的連線,則輸出"Yes",如果不存在符合條件的連線,輸出"No"。
Sample Input
2
4 3
1 2
1 3
1 4
4 5
1 2
2 3
1 3
1 4
3 4
Sample Output
No
Yes
解題思路:
AC程式碼:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int maxn=1005; 5 int T,n,m,deg[maxn],fa[maxn],a,b,f1,f2; 6 void init(){ 7 for(int i=1;i<=n;++i)fa[i]=i; 8 } 9 int findt(int x){ 10 int per=x,tmp; 11 while(fa[per]!=per)per=fa[per]; 12 while(x!=per){tmp=fa[x];fa[x]=per;x=tmp;} 13 return x; 14 } 15 void unite(int x,int y){ 16 x=findt(x),y=findt(y); 17 if(x!=y)fa[x]=y; 18 } 19 int main(){ 20 while(cin>>n>>m){ 21 memset(deg,0,sizeof(deg));init();f1=f2=0;///f1判斷是否是連通圖,f2統計每個節點的度 22 while(m--){ 23 cin>>a>>b; 24 deg[a]++,deg[b]++; 25 unite(a,b); 26 } 27 for(int i=1;i<=n;++i) 28 f1+=(i==fa[i]?1:0),f2+=(deg[i]&1?0:1); 29 if(f1==1&&(f2==n||n-f2==2))puts("Yes");///如果每個節點的度都是偶數,或者有兩個奇數度的節點,就能一筆畫出 30 else puts("No"); 31 32 } 33 return 0; 34 }