luogu P1084 [NOIP 2012 提高组] 疫情控制 题解
Solution
最大值最小化,考虑二分答案。
显然军队只会往上走,我们使用一个倍增就能知道军队最多走到哪里。
但是军队不能停留在根,那么对于能够走到根的军队,我们需要分配他们下降到根的儿子中那些堵不住的地方。
那么我们按照军队的剩余时间从小到大考虑,军队回到它原来属于的那个儿子费用为 \(0\),我们优先考虑匹配它原来的儿子,然后再考虑选择它能够选择的儿子中未被匹配并且边权最小的儿子尝试进行匹配。可以用一个单调队列来维护。
Code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=5e4+5,M=22;
const ll inf=1e18;
int n,m,a[N],top[N],c[N],C[N],cnt[N],tot[N];bool vis[N],F[N];
pair<int,ll> fa[N][M];
vector<pair<int,ll> > e[N];
vector<pair<ll,int> > v;
vector<int> V;
priority_queue<pair<ll,int>,vector<pair<ll,int> >,greater<pair<ll,int> > > q;
void dfs(int x,int f){
if(f!=1)top[x]=top[f];
for(int i=1;i<=20;i++)
fa[x][i]={fa[fa[x][i-1].first][i-1].first,fa[x][i-1].second+fa[fa[x][i-1].first][i-1].second};
for(auto i:e[x]){
int v=i.first;ll w=i.second;
if(v==f)continue;
fa[v][0]={x,w};
dfs(v,x);
}
}
void Dfs(int x,int f){
if(x!=1&&e[x].size()==1)V.push_back(top[x]);
for(auto i:e[x]){
int v=i.first;ll w=i.second;
if(v==f||vis[v])continue;
Dfs(v,x);
}
}
bool cmp(int x,int y){return c[x]<c[y];}
bool check(ll x){
v.clear();V.clear();
for(int i=1;i<=n;i++)vis[i]=cnt[i]=tot[i]=F[i]=0;
while(!q.empty())q.pop();
for(int i=1;i<=m;i++){
ll tmp=x,now=a[i];
for(int j=20;j>=0;j--){
if(fa[now][j].second<=tmp){
tmp-=fa[now][j].second;
now=fa[now][j].first;
}
}
if(now==1){
cnt[top[a[i]]]=1;
v.push_back({tmp,top[a[i]]});
}else vis[now]=1;
}
Dfs(1,0);
sort(V.begin(),V.end());
V.erase(unique(V.begin(),V.end()),V.end());
if(v.size()<V.size())return 0;
sort(v.begin(),v.end());
for(ll i:V){
F[i]=1;
q.push({c[i],i});
}
for(auto i:v){
if(cnt[i.second]&&F[i.second]){
cnt[i.second]--;
tot[i.second]++;
}else{
while(!q.empty()&&tot[q.top().second]){
tot[q.top().second]--;
q.pop();
}
if(q.empty())break;
if(i.first>=q.top().first){
cnt[q.top().second]=0;
q.pop();
}
}
}
while(!q.empty()&&tot[q.top().second]){
tot[q.top().second]--;
q.pop();
}
return q.empty();
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1;i<n;i++){
int u,v;ll w;cin>>u>>v>>w;
if(u==1||v==1){
if(v==1)swap(u,v);
c[v]=C[v]=w;
top[v]=v;
}
e[u].push_back({v,w});
e[v].push_back({u,w});
}
cin>>m;
for(int i=1;i<=m;i++)cin>>a[i];
fa[1][0].second=inf+1;
dfs(1,0);
ll l=0,r=1e18;
while(l<r){
ll mid=(l+r)>>1;
if(check(mid))r=mid;
else l=mid+1;
}
if(l==1e18)cout<<-1;
else cout<<l;
return 0;
}

浙公网安备 33010602011771号