UVA 10054 The Necklace (dfs欧拉回路)

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=18806

题意:给一些两色(两色可相同)的珠子,珠子相连的规则是相邻珠子接触部分的颜色相同,求这样的珠子的排列顺序并输出。

思路:比较明显的欧拉回路。

把一个珠子的两色连一条无向边,DFS找欧拉回路;

同时按照结束访问的顺序记录访问的点,就是欧拉回路的路径了。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 55;
int G[maxn][maxn], vis[maxn][maxn], ans[1005], num[maxn];
int n, a, b, cnt;
bool dfs(int u){   // 找欧拉回路
    for(int i = 1; i <= 50; i++){
        if(G[u][i] && vis[u][i] < G[u][i]){
            vis[u][i]++;
            vis[i][u]++;
            dfs(i);
        }
    }
    ans[cnt++] = u;  //  记录路径
}
int main(){
    int t, tc = 0;
    scanf("%d", &t);
    while(t--){
        cnt = 0;
        memset(G, 0, sizeof(G));
        memset(vis, 0, sizeof(vis));
        memset(num, 0, sizeof(num));
        if(tc) printf("\n");
        scanf("%d", &n);
        for(int i = 0; i < n; i++){
            scanf("%d %d", &a, &b);
            G[a][b]++;num[a]++;
            G[b][a]++;num[b]++;
        }
        dfs(a);
        int tag = 1;
        printf("Case #%d\n", ++tc);
        for(int i = 1; i <= 50; i++){  // 如果有点的度为奇数,则不能组成欧拉回路
            if(num[i]%2) tag = 0;
        }
        if(!tag || cnt != n+1) printf("some beads may be lost\n");
        else {
            for(int i = 0; i < cnt-1; i++)
                printf("%d %d\n", ans[i], ans[i+1]);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mad_boys/article/details/48691163