2017年5月16日 | ljfcnyali
题目大意
Farmer John每年有很多栅栏要修理。他总是骑着马穿过每一个栅栏并修复它破损的地方。
John是一个与其他农民一样懒的人。他讨厌骑马,因此从来不两次经过一个栅栏。你必须编一个程序,读入栅栏网络的描述,并计算出一条修栅栏的路径,使每个栅栏都恰好被经过一次。John能从任何一个顶点(即两个栅栏的交点)开始骑马,在任意一个顶点结束。
每一个栅栏连接两个顶点,顶点用1到500标号(虽然有的农场并没有500个顶点)。一个顶点上可连接任意多(>=1)个栅栏。两顶点间可能有多个栅栏。所有栅栏都是连通的(也就是你可以从任意一个栅栏到达另外的所有栅栏)。
你的程序必须输出骑马的路径(用路上依次经过的顶点号码表示)。我们如果把输出的路径看成是一个500进制的数,那么当存在多组解的情况下,输出500进制表示法中最小的一个 (也就是输出第一位较小的,如果还有多组解,输出第二位较小的,等等)。
输入数据保证至少有一个解。
Sample Input
9
1 2
2 3
3 4
4 2
4 5
2 5
5 6
5 7
4 6
Sample Output
1
2
3
4
2
5
4
6
5
7
题目分析
DFS爆搜过去,主要是要判断一下起点。
AC代码
/*
LANG: C++
ID: jerry272
PROG: fence
*/
/*************************************************************************
> File Name: USACO3.2.5-butter.cpp
> Author: ljf-cnyali
> Mail: ljfcnyali@gmail.com
> Created Time: 2017/5/16 20:44:24
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>
using namespace std;
#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++ i)
#define mem(a) memset((a), 0, sizeof(a))
#define str(a) strlen(a)
const int maxn = 1010;
const int maxm = 1000010;
int Map[maxn][maxn], f[maxn], res[maxm];
int cnt, n;
void go(int x) {
REP(i, 1, n)
if ( Map[x][i]) {
-- Map[x][i];
-- Map[i][x];
go(i);
}
res[ ++ cnt] = x;
}
int main() {
freopen("fence.in", "r", stdin);
freopen("fence.out", "w", stdout);
scanf("%d", &n);
int x, y;
REP(i, 1, n) {
scanf("%d%d", &x, &y);
++ Map[x][y];
++ Map[y][x];
++ f[x];
++ f[y];
n = max ( n, max ( x, y));
}
int find = 0;
REP(i, 1, n)
if ( f[i] % 2 == 1) {
find = i;
break ;
}
if ( find == 0)
REP(i, 1, n)
if ( f[i] > 0) {
find = i;
break ;
}
go(find);
for ( int i = cnt; i >= 1; -- i)
printf("%d\n", res[i]);
return 0;
}