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

13 篇文章 0 订阅
1 篇文章 0 订阅

欧拉路问题。


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


欧拉路算法:


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


假如不是欧拉回路,只是欧拉路,那么……   一个点的出度=入度+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;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值