D - Transit Tree Path
Description
Input
Output
Sample Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Sample Output
3
2
4
Hint
题意
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
题解:
3
2
4
AC代码
DFS 代码
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define CLR(a,b) memset(a,(b),sizeof(a))
const int INF = 0x3f3f3f3f;
const LL INFLL = 0x3f3f3f3f3f3f3f3f;
const int N = 1e5+10;
vector<pair<int,int> > G[N];
LL par[N];
int dfs(int x,int y)
{
for(int i = 0; i < G[x].size(); i++) {
int j = G[x][i].first;
if(j == y) continue;
par[j] = par[x] + G[x][i].second;
dfs(j, x);
}
}
int main()
{
int n;
int x, y, z;
scanf("%d",&n);
for(int i = 0; i < n-1; i++) {
scanf("%d%d%d",&x,&y,&z);
G[x].push_back(make_pair(y,z));
G[y].push_back(make_pair(x,z));
}
int q, k;
scanf("%d%d",&q,&k);
par[k] = 0; dfs(k, -1);
while(q--) {
scanf("%d%d",&x,&y);
printf("%lld\n",par[x]+par[y]);
}
return 0;
}
LCA代码
#include<bits/stdc++.h>
using namespace std ;
typedef long long LL ;
const int MAXN = 1e5+100 ;
const int MAXM = 1e5 ;
const int mod = 1e9+7 ;
struct Edge {
LL from,to,val,next;
}edge[MAXN<<2];
LL head[MAXN],top;
LL n,m;
void init(){
memset(head,-1,sizeof(head));
top=0;
}
void addedge(LL a,LL b,LL c){
Edge e={a,b,c,head[a]};
edge[top]=e;head[a]=top++;
}
void getmap(){
LL a,b,c;
while(m--){
scanf("%lld%lld%lld",&a,&b,&c);
addedge(a,b,c);
addedge(b,a,c);
}
}
LL fa[MAXN][50+5],depth[MAXN];
LL dist[MAXN];
void dfs(LL now,LL par){
fa[now][0]=par;
for(LL i=1;i<50;i++){
fa[now][i]=fa[fa[now][i-1]][i-1];
}
for(LL i=head[now];i!=-1;i=edge[i].next){
Edge e=edge[i];
if(e.to!=par){
dist[e.to]=dist[now]+e.val;
depth[e.to]=depth[now]+1;
dfs(e.to,now);
}
}
}
LL lca(LL a,LL b){
if(depth[a]<depth[b]) swap(a,b);
for(LL i=49;i>=0;i--){
if(depth[fa[a][i]]>=depth[b]){
a=fa[a][i];
}
}
if(a==b) return b;
for(LL i=49;i>=0;i--){
if(fa[a][i]!=fa[b][i]){
a=fa[a][i];
b=fa[b][i];
}
}
return fa[b][0];
}
void solve(){
depth[1]=0;dist[1]=0;
dfs(1,-1);
LL q,k;
scanf("%lld%lld",&q,&k);
while(q--){
LL a,b;
scanf("%lld%lld",&a,&b);
LL dis1=dist[a]+dist[k]-2*dist[lca(a,k)];
LL dis2=dist[b]+dist[k]-2*dist[lca(b,k)];
printf("%lld\n",dis1+dis2);
}
}
int main(){
scanf("%lld",&n);m=n-1;
init();
getmap();
solve();
}