比赛 NOIP2023模拟赛3 评测结果 WWWWTTTTTT
题目名称 树权 最终得分 0
用户昵称 ┭┮﹏┭┮ 运行时间 12.081 s
代码语言 C++ 内存使用 43.89 MiB
提交时间 2023-11-15 12:59:47
显示代码纯文本
#include <bits/stdc++.h> 
using namespace std;
typedef long long ll;
const int N = 1e6+10;
int n,m;
ll ans;
struct side{
    int ver,nx;
}e[N<<1];
int hd[N],tot;
void add(int x,int y) {
    tot++;
    e[tot].ver = y,e[tot].nx = hd[x],hd[x] = tot;
}
struct made{
    int l,r;
    bool operator <(const made u)const{
        if(l == u.l)return r < u.r;
        else return l < u.l;
    }
}a[N],v[N];
int r[N],cnt = 0;
void dfs(int x,int fa){
    if(x <= m)return;
    int st = cnt;
    for(int i = hd[x];i;i = e[i].nx){
        int y = e[i].ver;
        if(y == fa)continue;
        dfs(y,x);
        v[++cnt].l = a[y].l;v[cnt].r = a[y].r;
    }
    int ed = cnt;
    sort(v+1+st,v+1+cnt);
    priority_queue<int,vector<int>,greater<int> >q;
    map<int,bool>mp;
    mp.clear();
    for(int i = st+1;i <= cnt;i++){
        q.push(v[i].l),mp[v[i].l] = true;
        q.push(v[i].r),mp[v[i].r] = true;
    }
    int l = q.size()-1;
    int mid = (l % 2 == 0?l/2:l/2+1);
    for(int i = 1;i < mid;i++)q.pop();
    a[x].l = q.top();q.pop();
    a[x].r = q.top();q.pop();
    for(int i = hd[x];i;i = e[i].nx){
        int y = e[i].ver;
        if(y == fa)continue;
        ans += min(abs(a[x].r-a[y].r),abs(a[x].r-a[y].l)); 
    } 
}
int main(){
    freopen("starria.in","r",stdin);
    freopen("starria.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i = 1;i < n;i++){
        int x,y;scanf("%d%d",&x,&y);
        add(x,y);
        add(y,x);
    }
    for(int i = 1;i <= m;i++){
        int x;scanf("%d",&x);
        a[i].l = a[i].r = x;
    }
    dfs(n,0);
    printf("%lld\n",ans);
    
    return 0;
    
}