典型的找欧拉路径的题。先贴下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轻松简单方便地就解决了。。。
/* ID: yingzho1 LANG: C++ TASK: fence */ #include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <set> #include <algorithm> #include <stdio.h> #include <queue> #include <cstring> #include <cmath> #include <list> #include <cstdio> #include <cstdlib> #include <limits> #include <stack> using namespace std; ifstream fin("fence.in"); ofstream fout("fence.out"); ; }; ]; int F, st, ans_tot; void dfs(int st) { ; i < MAX; i++) { if (edge[st][i]) { edge[st][i]--, edge[i][st]--; du[st]--, du[i]--; dfs(i); } } ans[++ans_tot] = st; } int main() { fin >> F; int x, y; ; i < F; i++) { fin >> x >> y; edge[x][y]++, edge[y][x]++; du[x]++, du[y]++; } st = ; ; i < MAX; i++) { ) { st = i; break; } } ) { ; i < MAX; i++) { if (du[i]) { st = i; break; } } } dfs(st); ; i--) fout << ans[i] << endl; ; }