您的位置:首页 > 其它

UVa:10054 The Necklace

2014-02-10 17:57 369 查看
大一的时候写这道题被卡到死,最终AC跑了1s多,不知为何。

今天重写,还是WA了好多次。

注意一些地方,要判断图是否联通,编号1——50不一定全部都出现,也不一定连续出现。

这样,并查集+欧拉回路即可。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define ll long long
#define INF 200000000
#define MOD 20071027
#define MAXN 1000005
using namespace std;
int father[55];
int find(int p)
{
    return p==father[p]?p:father[p]=find(father[p]);
}
int gl[55][55]= {0};
int maxn=0;
void Output(int u)
{
    for(int i=1; i<=maxn; ++i)
        if(gl[u][i]&&gl[i][u])
        {
            gl[u][i]--;
            gl[i][u]--;
            Output(i);
            printf("%d %d\n",i,u);
        }
}
int main()
{
    int T,kase=0;
    scanf("%d",&T);
    while(T--)
    {
        int N;
        scanf("%d",&N);
        int in[55]= {0};
        memset(gl,0,sizeof(gl));
        for(int i=0; i<=50; ++i)
            father[i]=i;
        maxn=0;
        for(int i=0; i<N; ++i)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            gl[x][y]++;
            gl[y][x]++;
            in[x]++;
            in[y]++;
            int fx=find(x),fy=find(y);
            if(fx!=fy) father[fx]=fy;
            maxn=max(maxn,max(x,y));
        }
        int u=0,v=0;
        for(int i=1; i<=maxn; ++i)
        {
            if(in[i]%2) u++;
            if(in[i]&&father[i]==i) v++;
        }
        printf("Case #%d\n",++kase);
        if(u||v!=1)puts("some beads may be lost");
        else  Output(maxn);
        if(T) printf("\n");
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: