Description
Farmer John's cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in "Navigation Nightmare",followed by a line containing a single integer K, followed by K "distance queries". Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ's distance queries as quickly as possible!Input
* Lines 1..1+M: Same format as "Navigation Nightmare"Output
* Lines 1..K: For each distance query, output on a single line an integer giving the appropriate distance.Sample Input
7 6 1 6 13 E 6 3 9 E 3 5 7 S 4 1 3 N 2 4 20 W 4 7 2 S 3 1 6 1 4 2 6
Sample Output
13 3 36
Hint
Farms 2 and 6 are 20+3+13=36 apart.Source
USACO 2004 February
求樹上兩個點最近距離
ac代碼
#include#include #include struct s { int u,v,w,next; }edge[100100]; struct que { int u,v,num,next; }q[100010]; int head1[100100],head2[100010],cnt1,cnt2,dis[100100],pre[100100],n,m,qq,vis[100100],ans[100100 ]; int find(int x) { if(x==pre[x]) return x; return find(pre[x]); } void init() { memset(head1,-1,sizeof(head1)); memset(head2,-1,sizeof(head2)); memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); cnt1=cnt2=0; } void add1(int u,int v,int w) { edge[cnt1].u=u; edge[cnt1].v=v; edge[cnt1].w=w; edge[cnt1].next=head1[u]; head1[u]=cnt1++; } void add2(int u,int v,int i) { q[cnt2].u=u; q[cnt2].v=v; q[cnt2].num=i; q[cnt2].next=head2[u]; head2[u]=cnt2++; } void tarjan(int u,int len) { int i,v; pre[u]=u; dis[u]=len; vis[u]=1; for(i=head2[u];i!=-1;i=q[i].next) { if(vis[q[i].v]) ans[q[i].num]=dis[u]+dis[q[i].v]-2*dis[find(q[i].v)]; } for(i=head1[u];i!=-1;i=edge[i].next) { v=edge[i].v; if(!vis[v]) { tarjan(v,len+edge[i].w); pre[v]=u; } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { init(); while(m--) { int a,b,c; char str[2]; scanf("%d%d%d%s",&a,&b,&c,str); add1(a,b,c); add1(b,a,c); } scanf("%d",&qq); int i; for(i=1;i<=qq;i++) { int a,b; scanf("%d%d",&a,&b); add2(a,b,i); add2(b,a,i); } tarjan(1,0); // int i; for(i=1;i<=qq;i++) { printf("%d\n",ans[i]); } } }