USACO Riding the fences and C implement

题目大意:


求欧拉图的路径,输入的第一行是边数 ,接下来的 条边,求这些边恰好经过一次的路径,如果存在多组解输出字典序最小的一组。


欧拉路径:从图的某一个顶点出发,图中每条边走且仅走一次,最后到达某一个点。如果这样的路径存在,则称之为欧拉路径

 

 

随机选择某一顶点,如果有度是奇数的顶点, 则从该顶点开始。然后随机选择一条与之相连的边,删除。递归访问与该边相连的节点,最后将该边存入路径,倒序输出即是一条欧拉路径

 

给出的图已经是包含欧拉路径了,所以不需要检测

 

 

基本思路: DFS,从某一点出发,深度搜索,向下递归。

题目要求输出的次序为 从小到大 所有搜索时的策略 是 从小到大搜

用一个栈来保存路径

下面举一个比较简单的例子:

USACO Riding the fences and C implement_第1张图片


USACO Riding the fences and C implement_第2张图片



INPUT FORMAT

Line 1: The number of fences, F (1 <= F <= 1024)
Line 2..F+1: A pair of integers (1 <= i, j <= 500) that tell which pair of intersections this fence connects.

SAMPLE INPUT (file fence.in)

9
1 2
2 3
3 4
4 2
4 5
2 5
5 6
5 7
4 6

OUTPUT FORMAT

The output consists of F+1 lines, each containing a single integer. Print the number of the starting intersection on the first line, the next intersection's number on the next line, and so on, until the final intersection on the last line. There might be many possible answers to any given input set, but only one is ordered correctly.

SAMPLE OUTPUT (file fence.out)

1
2
3
4
2
5
4
6
5
7


/*
ID: abc18711
LANG: C
TASK: fence
*/

#include <stdio.h>

#define MaxI 501   
#define MaxF 2048

#define Max(x, y) (x > y ? x : y)
#define Min(x, y) (x < y ? x : y)

int minInter, maxInter;
int adjMatrix[MaxI][MaxI];
int degree[MaxI];
int stackPath[MaxF];
int top = 0;



void dfs(int x)
{
	int i;
	if (degree[x])
	{
		do
		{
			for (i=minInter; i<=maxInter; i++)
			{
				if(adjMatrix[x][i]) //find the smallest adj intersection
					break;
			}
			adjMatrix[x][i]--;
			adjMatrix[i][x]--;
			degree[x]--;
			degree[i]--;
			dfs(i);
		}while (degree[x]);
		stackPath[top++] = x;
	}
	else
	{
		stackPath[top++] = x;
	}
}

void search()
{
	int i;
	for (i=minInter; i<=maxInter; i++)
	{
		if (degree[i] % 2 == 1) //search from the odd intersection if exists
		{
			dfs(i);
			return;
		}
	}
	dfs(minInter);   //if there is no odd intersection
	
}

int main()
{
	FILE *fin = fopen("fence.in", "r");
	FILE *fout = fopen("fence.out", "w");
	
	int numFen;
	int i;
	int s, t; //the start intersection of a fence, the terminal intersection of a fence
        int flag = 0;
	
	fscanf(fin, "%d", &numFen);
	
	minInter = 501;
	maxInter = 0;
	for (i=0; i<numFen; i++)
	{
		fscanf(fin, "%d %d", &s, &t);
		adjMatrix[s][t] ++;
		adjMatrix[t][s] ++;
		
		degree[s] ++;
		degree[t] ++;

		if (minInter > Min(s, t))
			minInter = Min(s, t);
		if (maxInter < Max(s, t))
			maxInter = Max(s, t);
	}
        
	search();

        for(i=top-1; i>=0; i--)
		fprintf(fout, "%d\n", stackPath[i]);

	fclose(fin);
	fclose(fout);
	return 0;
}



你可能感兴趣的:(USACO)