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;
        }
    }
}
目录
相关文章
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
132 0
|
存储 容器
华为机试HJ41:称砝码(深度优先遍历dfs-Depth First Search)
华为机试HJ41:称砝码(深度优先遍历dfs-Depth First Search)
142 0
|
机器学习/深度学习 Windows
The 2022 ICPC Asia Regionals Online Contest (I)-D题题解(DFS暴搜+剪枝+打表去重+二分)
时间复杂度:O(227 + nlog(n) + T * log(n)),227是DFS打表的时间,nlog(n)是vertor排序的时间,T*log(n)是询问次数和二分搜答案的时间。(如果算错了,评论或者私信指出谢谢)
168 0
The 2022 ICPC Asia Regionals Online Contest (I)-D题题解(DFS暴搜+剪枝+打表去重+二分)
UPC Graph (最小生成树 || 并查集+二分)
UPC Graph (最小生成树 || 并查集+二分)
92 0
|
定位技术
UPC——帕琪的药园(dfs或并查集)
UPC——帕琪的药园(dfs或并查集)
79 0
|
人工智能 vr&ar
SPOJ - COT Count on a tree(主席树 LCA)
SPOJ - COT Count on a tree(主席树 LCA)
93 0
|
机器学习/深度学习
[POJ] John‘s trip | 欧拉回路 | 边序列字典序最小 + 建图
Description Little Johnny has got a new car. He decided to drive around the town to visit his friends. Johnny wanted to visit all his friends, but there was many of them. In each street he had one friend. He started thinking how to make his trip as short as possible.
142 0
[POJ] John‘s trip | 欧拉回路 | 边序列字典序最小 + 建图
[Nowcoder] network | Tarjan 边双连通分量 | 缩点 | LCA倍增优化 | 并查集
题目描述 A network administrator manages a large network. The network consists of N computers and M links between pairs of computers. Any pair of computers are connected directly or indirectly by successive links, so data can be transformed between any two computers.
122 0
[Nowcoder] network | Tarjan 边双连通分量 | 缩点 | LCA倍增优化 | 并查集