How far away ?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 22960 Accepted Submission(s): 9073
Problem Description
There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this “How far is it if I want to go from house A to house B”? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path(“simple” means you can’t visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0
给你一棵树,每次询问求出任意两个点之间的距离
求树上任意两个点之间的距离,如果直接dfs的话2e2的询问,4e4的点,时间复杂度肯定会爆,于是可以想到用树上倍增来求LCA,再利用dis(u,v)=dis[u]+dis[v]-2*dis[lca(u,v)]求得两个点之间的距离,一道树上倍增的模板题。
#define push_back pb
#define make_pair mk
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using std::pair;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<double,int>PDI;
const double PI=acos(-1);
const int maxn=100000+10;
const int maxm=100000+10;
const int INF = 0x3f3f3f3f;
using namespace std;
struct node{int to,cost;};
int n,m,a,b;
vector g[maxn];
int d[maxn],pa[maxn][30],dep[maxn];
void dfs(int u,int fa,int deep,int dis)
{
d[u]=dis;
pa[u][0]=fa;
dep[u]=deep;
for(int i=0;iint v=g[u][i].to,w=g[u][i].cost;
if(v==fa) continue;
dfs(v,u,deep+1,dis+w);
}
}
void build()
{
for(int i=0;i<20;i++)
{
for(int j=1;j<=n;j++)
{
if(pa[j][i]<0) pa[j][i+1]=-1;
else pa[j][i+1]=pa[pa[j][i]][i];
}
}
}
int query(int x,int y)
{
if(dep[x]>dep[y]) swap(x,y);
for(int i=0;i<=20;i++)
if((dep[y]-dep[x])>>i&1)
y=pa[y][i];
if(x==y) return x;
for(int i=20;i>=0;i--)
{
if(pa[x][i]!=pa[y][i])
{
x=pa[x][i];
y=pa[y][i];
}
}
return pa[x][0];
}
int main()
{
int t;
cin>>t;
while(t--)
{
scanf("%d%d",&n,&m);
int u,v,w;
for(int i=1;i<=n;i++) g[i].clear();
for(int i=0;i1;i++)
{
scanf("%d%d%d",&u,&v,&w);
g[u].pb(node{v,w});
g[v].pb(node{u,w});
}
dfs(1,-1,1,0);
build();
while(m--)
{
scanf("%d%d",&a,&b);
int res=query(a,b);
printf("%d\n",d[a]+d[b]-2*d[res]);
}
}
}