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;
        }
    }
}
目录
相关文章
|
11月前
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
114 0
|
11月前
|
人工智能
poj 2299 Ultra-QuickSort 求逆序数 树状数组解法
所谓离散化,我们的了解就是对原数组排序,然后用所在位置的下标代替原数,这样我们就可以把数据范围缩小到1-500000,这个数组是开的下的。
35 0
|
11月前
|
存储 容器
华为机试HJ41:称砝码(深度优先遍历dfs-Depth First Search)
华为机试HJ41:称砝码(深度优先遍历dfs-Depth First Search)
105 0
POJ 3494 Largest Submatrix of All 1’s(单调栈)
POJ 3494 Largest Submatrix of All 1’s(单调栈)
|
人工智能
POJ 2299 Ultra-QuickSort(树状数组+离散化+求逆序数)
POJ 2299 Ultra-QuickSort(树状数组+离散化+求逆序数)
|
定位技术
UPC——帕琪的药园(dfs或并查集)
UPC——帕琪的药园(dfs或并查集)
68 0
codeforces1253——D. Harmonious Graph(并查集)
codeforces1253——D. Harmonious Graph(并查集)
83 0
UPC Graph (最小生成树 || 并查集+二分)
UPC Graph (最小生成树 || 并查集+二分)
86 0
|
机器学习/深度学习
POJ-1321,棋盘问题(DFS)
POJ-1321,棋盘问题(DFS)
|
机器学习/深度学习
HDU-2553,N皇后问题(DFS+回溯)
HDU-2553,N皇后问题(DFS+回溯)