USACO Section 3.3: Riding the Fences

典型的找欧拉路径的题。先贴下USACO上找欧拉路径的法子:

  • Pick a starting node and recurse on that node. At each step:
    • If the node has no neighbors, then append the node to the circuit and return
    • If the node has a neighbor, then make a list of the neighbors and process them (which includes deleting them from the list of nodes on which to work) until the node has no more neighbors
    • To process a node, delete the edge between the current node and its neighbor, recurse on the neighbor, and postpend the current node to the circuit。

但实际写的时候其实用DFS起来更加方便。这道题我一开始用stack,但是始终不能找到输出的序列在500位制情况下最小的解,于是从网上看到有人用dfs轻松简单方便地就解决了。。。

 1 /*

 2 ID: yingzho1

 3 LANG: C++

 4 TASK: fence

 5 */

 6 #include <iostream>

 7 #include <fstream>

 8 #include <string>

 9 #include <map>

10 #include <vector>

11 #include <set>

12 #include <algorithm>

13 #include <stdio.h>

14 #include <queue>

15 #include <cstring>

16 #include <cmath>

17 #include <list>

18 #include <cstdio>

19 #include <cstdlib>

20 #include <limits>

21 #include <stack>

22 

23 using namespace std;

24 

25 ifstream fin("fence.in");

26 ofstream fout("fence.out");

27 

28 const int MAX = 505;

29 

30 int edge[MAX][MAX] = {0};

31 int du[MAX], ans[MAX*3];

32 int F, st, ans_tot;

33 

34 void dfs(int st) {

35     for (int i = 1; i < MAX; i++) {

36         if (edge[st][i]) {

37             edge[st][i]--, edge[i][st]--;

38             du[st]--, du[i]--;

39             dfs(i);

40         }

41     }

42     ans[++ans_tot] = st;

43 }

44 

45 int main()

46 {

47     fin >> F;

48     int x, y;

49     for (int i = 0; i < F; i++) {

50         fin >> x >> y;

51         edge[x][y]++, edge[y][x]++;

52         du[x]++, du[y]++;

53     }

54     st = 0;

55     for (int i = 1; i < MAX; i++) {

56         if (du[i]%2) {

57             st = i;

58             break;

59         }

60     }

61     if (st == 0) {

62         for (int i = 1; i < MAX; i++) {

63             if (du[i]) {

64                 st = i;

65                 break;

66             }

67         }

68     }

69     dfs(st);

70     for (int i = ans_tot; i >= 1; i--) fout << ans[i] << endl;

71 

72     return 0;

73 }

 

你可能感兴趣的:(USACO)