您的位置:首页 > Web前端

USACO Riding the fences and C implement

2015-09-05 08:15 411 查看
题目大意:求欧拉图的路径,输入的第一行是边数 m ,接下来的 m 条边,求这些边恰好经过一次的路径,如果存在多组解输出字典序最小的一组。欧拉路径:从图的某一个顶点出发,图中每条边走且仅走一次,最后到达某一个点。如果这样的路径存在,则称之为欧拉路径随机选择某一顶点,如果有度是奇数的顶点, 则从该顶点开始。然后随机选择一条与之相连的边,删除。递归访问与该边相连的节点,最后将该边存入路径,倒序输出即是一条欧拉路径给出的图已经是包含欧拉路径了,所以不需要检测基本思路: DFS,从某一点出发,深度搜索,向下递归。题目要求输出的次序为 从小到大 所有搜索时的策略 是 从小到大搜用一个栈来保存路径下面举一个比较简单的例子:

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 thelast 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: abc18711LANG: CTASK: 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 intersectionbreak;}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 fenceint 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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: