修建小鎮的時候,爲了讓小鎮有特色,鎮長特地只修了n-1條路,並且規定說,所有在勇氣小鎮的村民,每一次出門必須規劃好路線,
路線必須滿足在到達終點之前絕對不走回頭路。每個人都要這樣,不然那個人就不配在小鎮生活下去,因爲他沒有這個勇氣。
事實上,這並不能算一項挑戰,因爲n-1條路已經連通了每戶人家,不回頭地從起點到終點,只是一個時間上的問題。
由於小鎮上的福利特別好,所以小懶入住了這個小鎮,他規劃了m次的行程,每次從L房屋到R房屋,他想問你他每次從L房屋到R房屋最少能走多少路。
Input
輸入的第一行是一個整數t,表示有t組數據
每組數據第一行是n,m兩個數字,分別表示小鎮上房屋的個數,和小懶計劃的行程的數量。
之後第2行到第n行,每行三個整數a,b,c表示,a房屋與b房屋之間連接着一條距離爲c的小路。
第n+1行到第n+m行,每行兩個整數,L,R,代表一次小懶的詢問,也就是詢問小懶從L房屋走到R房屋所走的最近距離爲多少。
Output
對於每組測試數據輸出m行,每行一個整數,代表小懶從詢問的L到R需要走的最近的距離
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
t<=10,2<=n<=40000,1<=m<=200,1<=a<=n,1<=b<=n,1<=c<=40000,1<=L<=n,1<=R<=n
最短路或LCA或BFS
#include<bits/stdc++.h>
#define ll long long
#define maxn 40010
#define INF 0x3f3f3f3f
using namespace std;
struct edge
{
ll to;
ll cost;
};
ll d[maxn];
int n,m;
vector<edge> v[maxn];
void dijkstra(ll s)
{
typedef pair<ll, ll> P;
priority_queue<P,vector<P>,greater<P> > que;
fill(d,d+n+1,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty())
{
P p=que.top();
que.pop();
ll V=p.second;
if(d[V]<p.first)
continue;
for(int i=0;i<v[V].size();i++)
{
edge e=v[V][i];
if(d[e.to]>d[V]+e.cost)
{
d[e.to]=d[V]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<=maxn;i++)
v[i].clear();
int t=n-1;
while(t--)
{
ll s,e,c;
scanf("%lld%lld%lld",&s,&e,&c);
edge p;
p.to=e;
p.cost=c;
v[s].push_back(p);
// for(int i=0;i<v[s].size();i++)
// printf("%lld %lld %lld\n",s,v[s][i].to,v[s][i].cost);
p.to=s;
v[e].push_back(p);
// for(int i=0;i<v[e].size();i++)
// printf("%lld %lld %lld\n",e,v[e][i].to,v[e][i].cost);
}
while(m--)
{
ll s,e;
scanf("%lld%lld",&s,&e);
dijkstra(s);
// for(int i=1;i<4;i++)
// printf("%lld ",d[i]);
// printf("\n");
printf("%lld\n",d[e]);
}
if(T!=0)
printf("\n");
}
return 0;
}