UVa11054 歐拉迴路

來源:互聯網
上載者:User

標籤:blog   http   使用   os   io   for   

題意:有一種彩色珠子連成項鏈,每個珠子的兩半由不同顏色組成,相鄰的兩個珠子接觸的要相同顏色。是否有一個串法,如果有就輸出順序。

思路:如果把每個顏色建一個點,那麼一個珠子就可以拆分成兩個點,再加一條邊,這樣問題就轉化成了求歐拉迴路。

判斷歐拉迴路,首先要是連通的,再者是每個點都要有偶數個度。要連通可以使用並查集。

代碼:

//http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=995#include<stdio.h>#include<string.h>const int maxn = 80;int map[maxn][maxn];int deg[maxn];int fa[maxn];int n,maxv;int find(int x){while(fa[x] != x)x = fa[x];return x;}void Union(int a,int b){int x = find(a);int y = find(b);if(x != y)fa[x] = y;}void DFS(int u)//歐拉迴路{for(int v =1;v<=maxv;v++){if(map[u][v]){map[u][v]--;map[v][u]--;//printf("%d %d\n",u,v);DFS(v); //路徑必須回溯時輸出printf("%d %d\n",v,u);}}}bool degOK(){for(int i=1;i<= maxv;i++)if(deg[i]%2)return false;return true;}inline int max(int a,int b){if(a > b)return a;return b;}void init(){maxv=0;memset(map,0,sizeof(map));memset(deg,0,sizeof(deg));for(int i=0;i<maxn;i++)fa[i] = i;}int main(){int t,i;int u,v;scanf("%d",&t);int cas = 0;while(t--){init();scanf("%d",&n);for(i=1;i<= n;i++){scanf("%d%d",&u,&v);map[u][v] ++;map[v][u] ++;deg[u]++;deg[v]++;Union(u,v); //判斷圖的連通性maxv = max(maxv,u);maxv = max(maxv,v);}int set = 0;for(i=1;i<=maxv;i++){if(deg[i] && fa[i] == i)set++;}if(cas)  printf("\n");printf("Case #%d\n",++cas);if(set >1 || !degOK())printf("some beads may be lost\n");elseDFS(maxv);}return 0;}/*251 22 33 44 55 652 12 23 43 12 4  */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.