原题:http://poj.org/problem?id=1986
题意:有n个点,m条边,下面m行给定一棵树(后面那个字母并没有什么卵用);
Q个询问,求两点间最短距离;
话说,我并没有考虑不连通的情况,然而也过了……另外,注意数组大小;
#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100005;
int head[N], fa[N][20], dep[N];
int dis[N];
int n, m, e;
queue<int>q;
struct node
{
int to, nex, val;
}edge[N<<1];
void add(int u, int v, int w)
{
edge[e].to = v;
edge[e].val = w;
edge[e].nex = head[u];
head[u] = e++;
}
void bfs(int root)
{
fa[root][0] = root;
dis[root] = 0;
dep[root] = 0;
q.push(root);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i = 1;i<20;i++)
fa[u][i] = fa[fa[u][i-1]][i-1];
for(int i = head[u];i!=-1;i = edge[i].nex)
{
int v = edge[i].to;
if(v == fa[u][0])
continue;
dep[v] = dep[u]+1;
dis[v] = dis[u]+edge[i].val;
fa[v][0] = u;
q.push(v);
}
}
}
int lca(int x, int y)
{
if(dep[x]<dep[y])
swap(x, y);
for(int i = 0;i<20;i++)
{
if((dep[x]-dep[y])&(1<<i))
x = fa[x][i];
}
if(x == y)
return x;
for(int i = 19;i>=0;i--)
{
if(fa[x][i]!=fa[y][i])
{
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
int main()
{
while(scanf("%d%d", &n, &m)!=EOF)
{
e = 0;
memset(head, -1, sizeof(head));
while(m--)
{
int u, v, w;
char c;
scanf("%d%d%d%c", &u, &v, &w, &c);
getchar();
add(u, v, w);
add(v, u, w);
}
bfs(1);
int Q;
scanf("%d", &Q);
while(Q--)
{
int u, v;
scanf("%d%d", &u, &v);
printf("%d\n", dis[u]+dis[v]-2*dis[lca(u, v)]);
}
}
return 0;
}