UVa 10054 项链(The Necklace)__基本法(套圈法)_欧拉路_A_

题意

一串由彩色珠子连接而成的项链散掉了,掉回地上的珠子判断有没有捡完,并且按顺序排列好(一个珠子两边有颜色,相邻珠子接触部分颜色应相同)。

分析

可以转换为欧拉回路的问题,此处用基本法判断找出欧拉回路,并提前用每个点度数判断是否能构成欧拉回路。

AC代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#define INF 0x3f3f3f3f
#define MAX 1005
using namespace std;
int n,s;
int ka;
typedef pair<int,int> p;
queue<p>ans;

int mp[1005][1005];
int into[1005];
int up;

void dfs(int u)
{
    int f=0;
    for(int i=0;i<1001;i++){
        if(mp[u][i]!=0){
            mp[u][i]--;
            mp[i][u]--;
            dfs(i);
            f = 1;
        }
        if(f == 1){
            ans.push(make_pair(i,u));
            f = 0;
        }
    }

}

void solve()
{
    dfs(s);
    int count1=0;
    stack<p>c;
    while(!ans.empty()){
        p ha,he;
        ha = ans.front();
        ans.pop();
        he.first = ha.second;
        he.second = ha.first;
        c.push(he);
        count1++;
    }

    for(int i=0;i<count1;i++){
        p ha;
        ha = c.top();
        c.pop();
        printf("%d %d\n",ha.first,ha.second);
    }
}

int main()
{
    int t;
    ka = 0;
    scanf("%d",&t);
    while(t--){
        memset(mp,0,sizeof(mp));
        memset(into,0,sizeof(into));
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            if(i == 0)
                s = a;
            mp[a][b]++;
            mp[b][a]++;
            into[a]++;
            into[b]++;
        }
        int flag = 0;
        for(int i=0;i<1001;i++){
            if(into[i]%2 != 0){
                flag = 1;
                break;
            }
        }
        printf("Case #%d\n",++ka);
        if(flag == 1){
            printf("some beads may be lost\n");
        }
        else{
            solve();
        }
        if(t!=0){
            printf("\n");
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值