90pts,TLEon#7#8求优化
查看原帖
90pts,TLEon#7#8求优化
1263684
Elysialr楼主2024/11/8 11:43
#include <bits/stdc++.h>
using namespace std;
#define val(k) f[r[x][k].ver].bot+r[x][k].cost
#define ll long long
#define SIZE 50001

inline ll read(){
	ll x=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9'){x=(x*10+ch-48);ch=getchar();}
	return x*f;
}
struct road{
    ll ver,cost;
};
struct node{
    ll fa,dis,bot;
};

ll n,m,res,sum,pos,tot;
vector<road> r[SIZE];
node f[SIZE];

bool cmp(road r1,road r2){
    return f[r1.ver].bot+r1.cost>f[r2.ver].bot+r2.cost;
}
void dfs(ll x){
    f[x].bot=0;
    if(r[x].empty()) return;

    for(ll i=0;i<r[x].size();i++)
    dfs(r[x][i].ver);
    sort(r[x].begin(),r[x].end(),cmp);
    map<ll,bool> vis;
    ll bot;

    for(bot=0;bot<r[x].size()&&val(bot)>=pos;bot++){
        vis[bot]=true;
        tot++;
    }
    for(ll i=r[x].size()-1;i>=bot;i--){
        ll j=bot;
        if(i<=j) break;
        if(vis[i]) continue;
        if(val(i)+val(j)<pos) continue;
        while(j+1<i&&val(i)+val(j+1)>=pos) j++;
        while(j>=bot&&vis[j]) j--;
        if(j<bot) break;

        tot++;
        vis[i]=true;
        vis[j]=true;
        while(vis[bot]) bot++;
    }
    if(bot<r[x].size()) 
    f[x].bot=val(bot);
}
bool check(ll x){
    pos=x;
    tot=0;
    dfs(1);
    return tot>=m;
}

void init(){
    n=read();
    m=read();
    for(ll i=1;i<n;i++){
        road y;
        ll x=read();
        y.ver=read();
        y.cost=read();
        r[x].push_back(y);
        swap(x,y.ver);
        r[x].push_back(y);
        sum+=y.cost;
    }
}
void prepare(){
    queue<ll> q;
    q.push(1);
    while(!q.empty()){
        ll x=q.front();q.pop();
        for(ll i=0;i<r[x].size();i++){
            ll y=r[x][i].ver;
            ll z=r[x][i].cost;
            if(y!=f[x].fa){
                f[y].dis=f[x].dis+z;
                f[y].fa=x;
                q.push(y);
            }
            else{
                r[x][i]=r[x].back();
                r[x].pop_back();
                i--;
            }
        }
    }
}
void solve(){
    while(res<sum){
        ll mid=(res+sum+1)>>1;
        if(check(mid)) res=mid;
        else sum=mid-1;
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    init();
    prepare();
    solve();
    cout<<res;
    return 0;
}

测评记录

2024/11/8 11:43
加载中...