设为首页 加入收藏

TOP

POJ 题目1986 Distance Queries(LCA 离线)
2015-11-21 01:01:08 来源: 作者: 【 】 浏览:1
Tags:POJ 题目 1986 Distance Queries LCA 离线
Distance Queries
Time Limit: 2000MS ? Memory Limit: 30000K
Total Submissions: 10142 ? Accepted: 3575
Case Time Limit: 1000MS

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"

* Line 2+M: A single integer, K. 1 <= K <= 10,000

* Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms.

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]); } } } 
    
   
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇BZOJ 2613 Poi2003 Shuffle 数论 下一篇Codeforces #200(div.2) 模拟练习..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: