参考: http://www.cppblog.com/Ylemzy/articles/100050.html
注意path数组长度为1025(edge的个数),刚开始弄成501(vertex个数)结果test 8 爆栈了
/*
ID: wangxin12
PROG: fence
LANG: C++
*/
#include <iostream>
#include <fstream>
#define MAX 505
#define Max(a,b) (a > b ? a : b)
#define Min(a,b) (a < b ? a : b)
using namespace std;
int map[MAX][MAX], num[MAX], path[1050]; //map¹¹Í¼£¬ num¼ÇÔØÿ¸öµã¶ÈÊý£¬path¼ÇÔØ·¾¶
int minn, maxn, index = 0; //ÒòΪÌâÄ¿ÖÐvertex²»´Ó1¿ªÊ¼£¬ÒªÔÚ¶ÁÈëÊý¾ÝµÄʱºò¼ÇÔØvertexµÄ×îС×î´óÖµ
void circle(int x) {
int i;
if(num[x]) {
do {
for(i = minn; i <= maxn; i++) {
if(map[x][i])
break;
} //find the smallest neighbor
map[x][i]--, map[i][x]--;
num[x]--, num[i]--; //delete this edge
circle(i); //
} while ( num[x] );
path[index++] = x;
}
else
path[index++] = x;
}
void deal() {
int i;
for(i = minn; i <= maxn; i++) {
if(num[i] % 2 == 1) {
circle(i);
return;
}
}
circle(minn);
}
int main() {
ifstream fi("fence.in");
ofstream fo("fence.out");
//intput
int n, from, to, i;
fi>>n;
for(i = 1, minn = 500, maxn = 1; i <= n; i++) {
fi>>from>>to;
map[from][to]++, map[to][from]++;
num[from]++, num[to]++;
if( minn > Min(from, to) ) minn = Min(from, to);
if( maxn < Max(from, to) ) maxn = Max(from, to);
}
deal();
//output
for(int j = index - 1; j >= 0; j--) {
fo<<path[j]<<endl;
}
fi.close();
fo.close();
return 0;
}