【USACO 3.3】(fence) Riding the Fences

-----------Prob-----------

Farmer John owns a large number of fences that must be repaired annually. He traverses the fences by riding a horse along each and every one of them (and nowhere else) and fixing the broken parts.

Farmer John is as lazy as the next farmer and hates to ride the same fence twice. Your program must read in a description of a network of fences and tell Farmer John a path to traverse each fence length exactly once, if possible. Farmer J can, if he wishes, start and finish at any fence intersection.

Every fence connects two fence intersections, which are numbered inclusively from 1 through 500 (though some farms have far fewer than 500 intersections). Any number of fences (>=1) can meet at a fence intersection. It is always possible to ride from any fence to any other fence (i.e., all fences are "connected").

Your program must output the path of intersections that, if interpreted as a base 500 number, would have the smallest magnitude.

There will always be at least one solution for each set of input data supplied to your program for testing.

------------Solution------------

贴心的USACO在这道题前面给了一篇文章,内容是EulerianTour,链接里面是文章翻译。

本题就是求一个欧拉路,题目中已经明示一定有解,不用判定无解了。。

但是这个题有渣渣的东西哟亲~~~~~两点之间可以有很多路哟亲~~~~~~都要走一边哟~~~~

--------------Code--------------

/*
ID:zst_0111
LANG:C++
TASK:fence
*/
#include<stdio.h>
#include<stdlib.h>

int a[501][501];
int dg[501];
int ans[5001];
int top,n;

int max(int x,int y)
{
    return x>y?x:y;
}

void find(int vec)
{
    int i;
    for(i=1;i<=n;i++)
        if(a[vec][i])
        {
            --a[vec][i];
            --a[i][vec];
            find(i);
        }
    ans[++top]=vec;
}

int main()
{
    int i,j,k,m;
   
    freopen("fence.in","r",stdin);
    freopen("fence.out","w",stdout);
   
    scanf("%d",&m);
    n=0;
    for(i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        ++a[x][y];
        ++a[y][x];
        dg[x]++;
        dg[y]++;
        n=max(n,max(x,y));
    }
   
    int start=-1;
   
    for(i=1;i<=n;i++)
        if(dg[i]&1)
        {
            start=i;
            break;
        }
    if(start==-1)
        for(i=1;i<=n;i++)
            if(dg[i])
            {
                start=i;
                break;
            }
    find(start);
    for(i=top;i>=1;i--)
        printf("%d\n",ans[i]);
    return 0;
}

posted on 2011-09-04 22:12  青色有角三倍速  阅读(173)  评论(0编辑  收藏  举报