当前位置: 代码迷 >> 综合 >> BZOJ1602 [Usaco2008 Oct]牧场行走
  详细解决方案

BZOJ1602 [Usaco2008 Oct]牧场行走

热度:84   发布时间:2023-12-14 17:01:04.0

标签:,LCA

Description

N头牛(2<=n<=1000)别人被标记为1到n,在同样被标记1到n的n块土地上吃草,第i头牛在第i块牧场吃草。 这n块土地被n-1条边连接。 奶牛可以在边上行走,第i条边连接第Ai,Bi块牧场,第i条边的长度是Li(1<=Li<=10000)。 这些边被安排成任意两头奶牛都可以通过这些边到达的情况,所以说这是一棵树。 这些奶牛是非常喜欢交际的,经常会去互相访问,他们想让你去帮助他们计算Q(1<=q<=1000)对奶牛之间的距离。

Input

*第一行:两个被空格隔开的整数:N和Q

 *第二行到第n行:第i+1行有两个被空格隔开的整数:AI,BI,LI

*第n+1行到n+Q行:每一行有两个空格隔开的整数:P1,P2,表示两头奶牛的编号。

Output

*第1行到第Q行:每行输出一个数,表示那两头奶牛之间的距离。

Sample Input

4 2

2 1 2

4 3 2

1 4 3

1 2

3 2

Sample Output

2

7

 

模板水题

再一次珍惜刷水机会

Code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#ifdef WIN32
#define LL "%I64d\n"
#else
#define LL "%lld\n"
#endif
using namespace std;
inline ll read()
{ll f=1,x=0;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;
}
const int maxn=1006;
struct edge{int to,next,w;}e[maxn<<1];
bool vis[maxn];
ll n,q,deep[maxn],dis[maxn],fa[maxn][11],last[maxn],cnt=0;void dfs(int x)
{vis[x]=1;rep(i,1,10){if(deep[x]<(1<<i))break;fa[x][i]=fa[fa[x][i-1]][i-1];}
#define reg(x) for(int i=last[x];i;i=e[i].next)
#define v e[i].toreg(x){if(vis[v])continue;deep[v]=deep[x]+1;dis[v]=dis[x]+e[i].w;fa[v][0]=x;dfs(v);}
}
int lca(int x,int y)
{if(deep[x]<deep[y])swap(x,y);int t=deep[x]-deep[y];rep(i,0,10)if((1<<i)&t)x=fa[x][i];dep(i,10,0)if(fa[x][i]!=fa[y][i])x=fa[x][i],y=fa[y][i];if(x==y)return x;else return fa[x][0];
}
int main()
{n=read(),q=read();rep(i,1,n-1){int x=read(),y=read(),z=read();e[++cnt]=(edge){y,last[x],z};last[x]=cnt;e[++cnt]=(edge){x,last[y],z};last[y]=cnt;}//cout<<"R";dfs(1);rep(i,1,q){int x=read(),y=read();printf(LL,dis[x]+dis[y]-2*dis[lca(x,y)]);}return 0;
}


  相关解决方案