How far away ?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6422 Accepted Submission(s): 2411
Problem Description
There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to
answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road
connecting house i and house j,with length k(0
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.
Sample Input
2
3 2
1 2 10
3 1 15
1 2
2 3
2 2
1 2 100
1 2
2 1
Sample Output
10
25
100
100
Source
ECJTU 2009 Spring Contest
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=2586
題目大意:給一個帶權樹,m次詢問,求兩點之間的距離
題目分析:裸的LCA問題,采用離線的Tarjan算法
#include
#include
int const MAX = 40005;
struct Edge
{
int id, val; //當前邊序號,邊權
int next; //下一條
}e[2 * MAX];
int n, m, cnt;
//x, y表示詢問的起點和終點,z是x和y的LCA
int x[MAX], y[MAX], z[MAX];
//fa存祖先,dist存到根的距離,pre存父親
int fa[MAX], dist[MAX], pre[MAX];
bool vis[MAX];
void AddEdge(int u, int v, int w)
{
e[cnt].id = u;
e[cnt].val = w;
e[cnt].next = pre[v];
pre[v] = cnt++;
e[cnt].id = v;
e[cnt].val = w;
e[cnt].next = pre[u];
pre[u] = cnt++;
}
int Find(int x)
{
return x == fa[x] ? x : fa[x] = Find(fa[x]);
}
void tarjan(int k)
{
vis[k] = true;
fa[k] = k;
for(int i = 1; i <= m; i++)
{
if(x[i] == k && vis[y[i]])
z[i] = Find(y[i]);
if(y[i] == k && vis[x[i]])
z[i] = Find(x[i]);
}
for(int i = pre[k]; i != -1; i = e[i].next)
{
if(!vis[e[i].id])
{
dist[e[i].id] = dist[k] + e[i].val;
tarjan(e[i].id);
fa[e[i].id] = k;
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int u, v, w;
scanf("%d %d", &n, &m);
cnt = 0;
memset(pre, -1, sizeof(pre));
for(int i = 1; i < n; i++)
{
scanf("%d %d %d", &u, &v, &w);
AddEdge(u, v, w);
}
for(int i = 1; i <= n; i++)
x[i] = y[i] = z[i] = 0;
for(int i = 1; i <= m; i++)
{
scanf("%d %d", &u, &v);
x[i] = u;
y[i] = v;
}
memset(vis, false, sizeof(vis));
dist[1] = 0;
tarjan(1);
for(int i = 1; i <= m; i++)
printf("%d\n",dist[x[i]] + dist[y[i]] - 2 * dist[z[i]]);
}
}