POJ 1986 Distance Queries
Distance Queries
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 |
[Submit] [Go Back] [Status] [Discuss]
题目大意:
输入n和m,表示n个点m条边,下面m行是边的信息,两端点和权,后面的那个字母无视掉,没用的。接着k,下面k个询问lca,输出即可
LCA的模板
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 const int MAXN=1e5+10; 6 inline int read() 7 { 8 char c=getchar();int x=0,f=1; 9 while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} 10 while(c>='0'&&c<='9') x=x*10+c-48,c=getchar();return x*f; 11 } 12 int n,m,S=1; 13 int f[MAXN][21],deep[MAXN],g[MAXN]; 14 struct node 15 { 16 int u,v,w,nxt; 17 }edge[MAXN]; 18 int head[MAXN]; 19 int num=1; 20 inline void add_edge(int x,int y,int z) 21 { 22 edge[num].u=x; 23 edge[num].v=y; 24 edge[num].w=z; 25 edge[num].nxt=head[x]; 26 head[x]=num++; 27 } 28 void dfs(int now) 29 { 30 for(int i=head[now];i!=-1;i=edge[i].nxt) 31 if(deep[edge[i].v]==0) 32 { 33 deep[edge[i].v]=deep[now]+1; 34 f[edge[i].v][0]=now; 35 g[edge[i].v]=g[now]+edge[i].w; 36 dfs(edge[i].v); 37 } 38 39 } 40 inline void pre() 41 { 42 for(int i=1;i<=19;i++) 43 for(int j=1;j<=n;j++) 44 f[j][i]=f[f[j][i-1]][i-1]; 45 } 46 inline int LCA(int x,int y) 47 { 48 if(deep[x]<deep[y]) swap(x,y); 49 for(int i=19;i>=0;i--) 50 if(deep[f[x][i]]>=deep[y]) 51 x=f[x][i]; 52 if(x==y) return x; 53 54 for(int i=19;i>=0;i--) 55 if(f[x][i]!=f[y][i]) 56 x=f[x][i],y=f[y][i]; 57 return f[x][0]; 58 } 59 int main() 60 { 61 int T=1; 62 while(T--) 63 { 64 n=read();m=read(); 65 memset(head,-1,sizeof(head));num=1; 66 memset(f,0,sizeof(f)); 67 memset(deep,0,sizeof(deep)); 68 for(int i=1;i<=m;i++) 69 { 70 int x=read(),y=read(),z=read(); 71 add_edge(x,y,z); 72 add_edge(y,x,z); 73 } 74 int q=read(); 75 deep[S]=1; 76 dfs(S);pre(); 77 while(q--) 78 { 79 int x=read(),y=read(); 80 printf("%d\n",g[x]+g[y]-2*g[LCA(x,y)]); 81 } 82 } 83 84 return 0; 85 }
作者:自为风月马前卒
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。