【USACO3.3.1】骑马修栅栏 欧拉路

欧拉路问题。


有回路,有纯粹的欧拉路。


欧拉路算法:


所有点的入度出度有一个特殊的关系。


假如不是欧拉回路,只是欧拉路,那么……   一个点的出度=入度+1  就是起点      入度=出度+1 就是终点



假如是欧拉回路,那就随意了。



欧拉路的遍历,需要后序遍历,倒序输出。    如果用前序遍历,正序输出, 会出现一个如下问题:


A->B

B->A

A->B

B->C


显然应该是 A B A B C


但是前序遍历会走路成:ABC ??  一旦显走了ABC,就不对了…… 但是后面也明明可以是圈的~  所以要后续遍历


相关证明略


Executing...
   Test 1: TEST OK [0.003 secs, 3516 KB]
   Test 2: TEST OK [0.003 secs, 3516 KB]
   Test 3: TEST OK [0.003 secs, 3516 KB]
   Test 4: TEST OK [0.003 secs, 3516 KB]
   Test 5: TEST OK [0.003 secs, 3516 KB]
   Test 6: TEST OK [0.003 secs, 3516 KB]
   Test 7: TEST OK [0.003 secs, 3516 KB]
   Test 8: TEST OK [0.005 secs, 3516 KB]

All tests OK.
/*
TASK:fence
LANG:C++
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
 
int paths;
 
struct edge
{
	int dot;
	bool vis;
	edge *next;
	edge *rel;
	edge (int t, edge *p)
	{
		dot = t;
		next = p;
		vis = false;
	}
	edge(){}
}*e[505];
 
int degree[505];
 
inline void insert(int x, int y)
{
	e[x] = new edge(y, e[x]);
}
 
int st, ed;
typedef pair<int, edge*> PIE;
PIE sort_tmp[1000];
 
void list_qsort(edge *&a)
{
	int t = 0;
	while (a)
	{
		sort_tmp[t ++] = make_pair(-a -> dot, a);
		a = a -> next;
	}
	sort(sort_tmp, sort_tmp + t);
	for (int i = 0; i != t; ++ i)	
	{
		sort_tmp[i].second -> next = a;
		a = sort_tmp[i].second;
	}
}
 
void pg(edge *a)
{
	while (a)
	{
		cout << a -> dot << " ";
		a = a -> next;
	}
	cout<<endl;
}
 
void init()
{
	scanf("%d", &paths);
	while (paths--)
	{
		int a, b;
		scanf("%d%d", &a, &b);
		++ degree[a];
		++ degree[b];
		insert(a, b);
		insert(b, a);
		e[a] -> rel = e[b];
		e[b] -> rel = e[a];
	}
	for (int i = 1; i <= 500; ++ i)	list_qsort(e[i]);
	for (int i = 1; i <= 500; ++ i)
		if (degree[i])
		{
			st = ed = i;
			break;
		}
	for (int i = 1; i <= 500; ++ i)	
		if (degree[i] % 2)
		{
			st = i;
			break;
		}
	for (int i = 500; i >= 1; -- i)
		if (degree[i] % 2)
		{
			ed = i;
			break;
		}
}
 
int output[1000], tail = 0;
void dfs(int s)
{
	for (edge *i = e[s]; i; i = i -> next)
	{
		if (!i -> vis)
		{
			i -> vis = true;
			i -> rel -> vis = true;
		}else continue;
		int will = i -> dot;
		dfs(will);
		output[tail++] = s;
	}
}
 
void doit()
{
	dfs(st);
	for (int i = tail - 1; i >= 0; -- i)	printf("%d\n", output[i]);
	printf("%d\n", ed);
}
 
int main()
{
	freopen("fence.in", "r", stdin);
	freopen("fence.out", "w", stdout);
	init();
	doit();
	return 0;
}


你可能感兴趣的:(【USACO3.3.1】骑马修栅栏 欧拉路)