UVa302 - John's trip(并查集、欧拉回路、DFS)

简介: UVa302 - John's trip(并查集、欧拉回路、DFS)
#include <cstdio>#include <vector>#include <utility>#include <cstring>#include <climits>#include <algorithm>usingnamespacestd;
constintN=2000;
intdeg[N];
vector<pair<int, int>>adjList[N];
boolvis[N];
intans[N];
inttop;
intstart;
boolinput();
voidadd(intx, inty, intz);
voidsolve();
voiddfs(intu);
intmain()
{
#ifndef ONLINE_JUDGEfreopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endifwhile (input()) {
solve();
    }
return0;
}
boolinput()
{
intx, y, z;
scanf("%d%d", &x, &y);
if (x==0&&y==0) returnfalse;
start=min(x, y);
for (inti=0; i<N; i++) adjList[i].clear();
memset(deg, 0x00, sizeof(deg));
while (1) {
scanf("%d", &z);
add(x, y, z);
deg[x]++;
deg[y]++;
scanf("%d%d", &x, &y);
if (x==0&&y==0) break;
   }
returntrue;
}
voidadd(intx, inty, intz)
{
adjList[x].push_back(make_pair(z, y));;
adjList[y].push_back(make_pair(z, x));;
}
voidsolve()
{
boolok=true;
for (inti=0; i<N; i++) {
if (!adjList[i].empty()) {
if (deg[i] &1) {
ok=false;
break;
            }
sort(adjList[i].begin(), adjList[i].end());
        }
    }
if (!ok) {
printf("Round trip does not exist.\n\n");
return;
    }
top=0;
memset(vis, false, sizeof(vis));
dfs(start);
for (inti=top-1; i>=0; i--) {
printf("%d%s", ans[i], i?" ":"\n\n");
    }
}
voiddfs(intu)
{
for (size_ti=0; i<adjList[u].size(); i++) {
if (!vis[adjList[u][i].first]) {
vis[adjList[u][i].first] =true;
dfs(adjList[u][i].second);
ans[top++] =adjList[u][i].first;
        }
    }
}
目录
相关文章
|
7月前
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
|
9月前
|
算法
1091 zoj Knight Moves的BFS算法和DFS
1091 zoj Knight Moves的BFS算法和DFS
35 0
|
7月前
|
存储 容器
华为机试HJ41:称砝码(深度优先遍历dfs-Depth First Search)
华为机试HJ41:称砝码(深度优先遍历dfs-Depth First Search)
codeforces1253——D. Harmonious Graph(并查集)
codeforces1253——D. Harmonious Graph(并查集)
67 0
|
机器学习/深度学习
POJ-1321,棋盘问题(DFS)
POJ-1321,棋盘问题(DFS)
|
机器学习/深度学习
HDU-2553,N皇后问题(DFS+回溯)
HDU-2553,N皇后问题(DFS+回溯)
HDU-1142,A Walk Through the Forest(Dijkstra+DFS)
HDU-1142,A Walk Through the Forest(Dijkstra+DFS)