您的位置:首页 > 其它

uva 10938(dfs)

2014-02-05 19:06 316 查看
题意:在一棵树上求距离中点,若距离是奇数则输出中间两个点。

思路:看到题意第一反应是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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: