【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;
}

转载于:https://www.cnblogs.com/Aoi3x/archive/2011/09/04/2645363.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值