UVA 10054 The Necklace

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

无向图的欧拉回路

1.连通图:并查集判断

2.所有点的度数均为偶数:邻接表存储即可

AC代码:

#include <vector>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAX = 1010;

typedef pair <int, int> Pii;
int a[MAX],b[MAX],vis[MAX];
int v[55],father[55];
vector <Pii> vt[55];
vector <Pii> path;

void Init(){///初始化
    path.clear();
    memset(vis, 0, sizeof(vis));
    for(int i=0; i<=50; i++){
        father[i] = i;
        vt[i].clear();
        v[i] = 0;
    }
}

int Find(int x){
    if(x != father[x])
        father[x] = Find(father[x]);
    return father[x];
}

bool check(){///判断是否存在欧拉回路
    for(int i=0; i<=50; i++)
        if(v[i])
            if(Find(i) != Find(a[0]))
                return false;
    for(int i=0; i<=50; i++)
        if(vt[i].size() % 2)    return false;
    return true;
}

void DFS(int u){///深搜路径
    for(int i=0; i<vt[u].size(); i++){
        if(vis[vt[u][i].first]) continue;
        vis[vt[u][i].first] = 1;
        DFS(vt[u][i].second);
        path.push_back(Pii(vt[u][i].first, b[vt[u][i].first] == u));
    }
}

int main(){
    //freopen("in.txt", "r", stdin);
    int cas,t=0;
    scanf("%d",&cas);
    while(cas--){
        int n;
        Init();
        scanf("%d",&n);
        for(int i=0; i<n; i++){
            scanf("%d%d",&a[i],&b[i]);
            v[a[i]] = v[b[i]] = 1;
            father[Find(a[i])] = Find(b[i]);
            vt[a[i]].push_back(Pii(i, b[i]));
            vt[b[i]].push_back(Pii(i, a[i]));
        }
        if(t)   cout << endl;
        printf("Case #%d\n",++t);
        if(check() == false){
            cout << "some beads may be lost" << endl;
            continue;
        }
        for(int i=0; i<=50; i++){
            if(vt[i].size()){
                DFS(i);
                for(int j=path.size(); j>=1; j--){
                    int id = path[j-1].first;
                    if(path[j-1].second)    cout << b[id] << " " << a[id] << endl;
                    else    cout << a[id] << " " << b[id] << endl;
                }
                break;
            }
        }
    }
    //system("pause");
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值