uva 10938(dfs)
2014-02-05 19:06
316 查看
题意:在一棵树上求距离中点,若距离是奇数则输出中间两个点。
思路:看到题意第一反应是lca,再看一下数据量那么小。。。一定有什么简单的做法。其实只要dfs一下就可以了保存路径输出中间的两个点。
代码如下:
View Code
思路:看到题意第一反应是lca,再看一下数据量那么小。。。一定有什么简单的做法。其实只要dfs一下就可以了保存路径输出中间的两个点。
代码如下:
/************************************************** * Author : xiaohao Z * Blog : http://www.cnblogs.com/shu-xiaohao/ * Last modified : 2014-02-05 18:39 * Filename : uva_10938.cpp * Description : * ************************************************/ #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <queue> #include <stack> #include <vector> #include <set> #include <map> #define MP(a, b) make_pair(a, b) #define PB(a) push_back(a) using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<unsigned int,unsigned int> puu; typedef pair<int, double> pid; typedef pair<ll, int> pli; typedef pair<int, ll> pil; const int INF = 0x3f3f3f3f; const double eps = 1E-6; const int LEN = 10100; vector<int> Map[LEN]; int n, vis[LEN], path[LEN], ed; void dfs(int v, int dep) { vis[v] = 1; path[dep] = v; if(v == ed){ if(dep%2==0) printf("The fleas meet at %d.\n", path[dep/2]); else printf("The fleas jump forever between %d and %d.\n", min(path[dep/2], path[dep/2+1]), max(path[dep/2], path[dep/2+1])); } for(int i=0; i<Map[v].size(); i++){ if(!vis[Map[v][i]]) dfs(Map[v][i], dep+1); } } int main() { // freopen("in.txt", "r", stdin); int a, b, st; while(scanf("%d", &n)!=EOF && n){ for(int i=0; i<LEN; i++)Map[i].clear(); for(int i=0; i<n-1; i++){ scanf("%d%d", &a, &b); Map[a].PB(b); Map[b].PB(a); } int q; scanf("%d", &q); for(int i=0; i<q; i++){ scanf("%d%d", &st, &ed); memset(vis, 0, sizeof vis); memset(path, 0, sizeof path); dfs(st, 0); } } return 0; }
View Code
相关文章推荐
- UVA-10938 - Flea circus(dfs)
- UVA 10938 - Flea circus(dfs)
- uva 10938 - Flea circus(dfs)
- UVA 548 Tree 中序+后序构造二叉树dfs
- UVa 10985 Rings'n'Ropes / floyd + dfs
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- UVa 129 - Krypton Factor(DFS+回溯)
- UVA129 DFS+字符串处理
- UVA 10400 Game Show Math (dfs + 记忆化搜索)
- UVA 818 - Cutting Chains(暴力+dfs判环+位运算)
- 【UVA】10317 - Equating Equations(dfs + 剪枝)
- uva 10318(dfs+状态压缩)
- UVA-679車的摆放(DFS)
- UVA10624 - Super Number(dfs)
- uva585(dfs)
- UVA 725 除法(DFS搜索排列)
- UVa - 572 Oil Deposits ( DFS求连通块 )
- UVa 572 Oil Desposits (dfs 图 染色 八连通种子填充)
- uva 10344 23 out of 5 (DFS)
- Play on Words 单词 UVA 10129 (欧拉+dfs)