比赛 |
20250527CSP-S模拟 |
评测结果 |
|
题目名称 |
数据传输 |
最终得分 |
0 |
用户昵称 |
zjzhe |
运行时间 |
0.000 s |
代码语言 |
C++ |
内存使用 |
0.00 MiB |
提交时间 |
2025-05-27 15:57:40 |
显示代码纯文本
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;
int n,q,k,v[N],tot,cnt,id[N],head[N<<1],dfn[N],dep[N],FA[N],top[N],siz[N],b_son[N],low[N],dp[N];
struct edge{
int ne,v;
}e[N<<1];
void add(int u,int v){
e[++tot]={head[u],v};head[u]=tot;
}
void dfs1(int u,int fa){
siz[u]=1;
dep[u]=dep[fa]+1;
FA[u]=fa;
for(int i=head[u];i;i=e[i].ne){
int v=e[i].v;
if(v==fa) continue;
dfs1(v,u);
siz[u]+=siz[v];
if(!b_son[u]||siz[v]>siz[b_son[u]]){
b_son[u]=v;
}
}
}
void dfs2(int u,int fa,int Top){
dfn[u]=++cnt;
id[cnt]=u;
top[u]=Top;
if(b_son[u])
dfs2(b_son[u],u,Top);
for(int i=head[u];i;i=e[i].ne){
int v=e[i].v;
if(v==b_son[u]||v==fa) continue;
dfs2(v,u,v);
}
low[u]=cnt;
}
struct SegTree{
int val[N<<2],tag[N<<2],len[N<<2];
int lc(int x) {
return x<<1;
}
int rc(int x){
return x<<1|1;
}
void pushup(int x){
val[x]=val[lc(x)]+val[rc(x)];
}
void upd(int x,int v){
val[x]=val[x]+len[x]*1ll*v;
tag[x]=tag[x]+v;
}
void pushdown(int x){
if(tag[x]){
upd(lc(x),tag[x]);
upd(rc(x),tag[x]);
tag[x]=0;
}
}
void build(int x,int l,int r){
len[x]=r-l+1;val[x]=tag[x]=0;
if(l==r) {
val[x]=v[id[l]];
return;
}
int mid=(l+r)>>1;
build(lc(x),l,mid);
build(rc(x),mid+1,r);
pushup(x);
}
int query(int x,int ql,int qr,int l,int r){
if(ql<=l&&qr>=r) return val[x];
pushdown(x);
int mid=(l+r)>>1;
int res=0;
if(ql<=mid) res=res+query(lc(x),ql,qr,l,mid);
if(qr>mid) res=res+query(rc(x),ql,qr,mid+1,r);
return res;
}
}sg;
int query(int x,int y){
int res=0;
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]]) swap(x,y);
res+=sg.query(1,dfn[top[x]],dfn[x],1,n);
x=FA[top[x]];
}
if(dep[x]<dep[y]) swap(x,y);
res+=sg.query(1,dfn[y],dfn[x],1,n);
return res;
}
int query2(int x,int y){
memset(dp,0,sizeof(dp));
vector<int> vx,vy;
while(top[x]!=top[y]){
if(dep[top[x]]>dep[top[y]]){
for(int i=dfn[x];i>=dfn[top[x]];i--)
vx.push_back(v[id[i]]);
x=FA[top[x]];
} else {
for(int i=dfn[y];i>=dfn[top[y]];i--)
vy.push_back(v[id[i]]);
y=FA[top[y]];
}
}
if(dep[x]>dep[y]){
for(int i=dfn[x];i>=dfn[y];i--) vx.push_back(v[id[i]]);
} else {
for(int i=dfn[y];i>=dfn[x];i--) vy.push_back(v[id[i]]);
//for(int i=dfn[x];i<=dfn[y];i++) vx.push_back(v[id[i]]);
}
reverse(vy.begin(),vy.end());
for(auto i : vy){
vx.push_back(i);
}
dp[0]=vx[0];
dp[1]=vx[0]+vx[1];
int siz=vx.size();
for(int i=2;i<siz;i++){
dp[i]=min(dp[i-1],dp[i-2])+vx[i];
}
return dp[siz-1];
}
#undef int
int main(){
#define int long long
freopen("csp2022_transmit.in","r",stdin);
freopen("csp2022_transmit.out","w",stdout);
cin>>n>>q>>k;
for(int i=1;i<=n;i++) cin>>v[i];
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
add(a,b),add(b,a);
}
dfs1(1,0);
dfs2(1,0,1);
sg.build(1,1,n);
while(q--){
int s,t;
cin>>s>>t;
if(k==1){
cout<<query(s,t)<<'\n';
}
if(k==2){
cout<<query2(s,t)<<'\n';
}
}
return 0;
}