您的位置:首页 > Web前端

usaco Chapter 3 section 3.3 Riding the Fences

2009-12-08 18:10 316 查看
/*
Riding the Fences

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.

这题怎么说呢,就是典型的欧拉回路。通过这题学会了欧拉回路,而且也明白了问题不明白它就难,明白了它就不难。

存在欧拉回路分两种情况:

1、有的节点的度都为偶数 2、只有两个节点的度为奇数

(所有节点连成环) 一个入另一个出

然后欧拉回路的算法就是取出发节点pos,Euler(pos)

Euler(pos)

如果pos存在邻接点对每个临界点,取j,取临界点j,删除该边,调用Euler(j)

否者直接将j放入得到的欧拉回路数组中(注意此时,数组是倒序的,需要逆向输出)
*/
/*
ID: niepeng1
LANG: C++
TASK:fence
*/
#include <iostream>
#include<stdio.h>
#include <stdlib.h>
using namespace std;
#define Maxcon 502
#define MMax 100000
int map[Maxcon][Maxcon];
int degree[Maxcon];
int result[MMax];
int hdef=0,ldef=Maxcon,F,cnt;
FILE *in,*out;
int Euler(int pos)
{
int i;
for(i=ldef;i<=hdef;i++)
{
if(map[pos][i]>0)
{
map[pos][i]=--map[i][pos];
Euler(i);
}

}
result[cnt++]=pos;
return 0;
}
int main()
{
int a,b,i;
in=fopen("fence.in","r");
out=fopen("fence.out","w");
fscanf(in,"%d",&F);
for(i=0;i<F;i++)
{
fscanf(in,"%d %d",&a,&b);
map[a][b]=++map[b][a];
degree[a]++;
degree[b]++;
if( ldef > a)
ldef=a;
if(ldef > b)
ldef=b;
if(hdef < a)
hdef=a;
if(hdef < b)
hdef=b;
}
for(i=ldef;i<=hdef;i++)
if( degree[i] & 1 )
break;
if( i==hdef+1)
Euler(ldef);
else
Euler(i);
for(i=cnt-1;i>=0;i--)
fprintf(out,"%d/n",result[i]);
fclose(in);fclose(out);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: