把博客园图标替换成自己的图标
把博客园图标替换成自己的图标end

luogu P1084 疫情控制

题面传送门
很毒瘤的一道大模拟。
首先贪心让军队走到最上面的点,如果能走到根节点就停留在根节点下面。
然后查看哪几颗子树没有被封死。
对于有军队的根节点,让能走回来的军队出去调动,反之让其停留在当前节点。
然后就是细节。
代码实现:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
int n,m,k,x,y,fa[300039][20],lg[300039],a[300039],flag[300039],cur,fh,jh,nh,curs,d[300039],fxt,fxts;
long long l,r,z,mid,sum[300039][20],fin[300039],jun[300039],now[300039],anss;
struct yyy{int to;long long w;int z;}tmp;
struct ljb{
	int head,h[300039];
	yyy f[600039];
	inline void add(int x,int y,long long z){
		f[++head]=(yyy){y,z,h[x]};
		h[x]=head;
	}
}s,h;
inline void dfs(int x,int last){
	fa[x][0]=last;
	d[x]=d[last]+1;
	for(int k=1;k<=lg[d[x]];k++) fa[x][k]=fa[fa[x][k-1]][k-1],sum[x][k]=sum[x][k-1]+sum[fa[x][k-1]][k-1];
	int cur=s.h[x];
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last) sum[tmp.to][0]=tmp.w,dfs(tmp.to,x);
		cur=tmp.z;
	}
}
inline int lca(int x,long long time){
	for(int k=lg[d[x]];k>=0;k--)if(fa[x][k]!=1&&fa[x][k]!=0&&time>=sum[x][k]) time-=sum[x][k],x=fa[x][k];
	if(fa[x][0]==1&&time-sum[x][0]>0)h.add(x,1,time-sum[x][0])/*,printf("%d %d\n",xs,time-sum[xs][0])*/;
	else flag[x]=1;
	return x;
}
inline int dfs2(int x,int last){
	int cur=s.h[x],flags=0,ff=0;
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last) {
			flags=1;
			if(!flag[tmp.to])ff=dfs2(tmp.to,x);
		}
		cur=tmp.z;
	}
	if(!flags||ff) return 1;
	else return 0;
}
inline int check(long long mid){
	memset(flag,0,sizeof(flag));
	memset(jun,0,sizeof(jun));
	h.head=0;
	memset(h.h,-1,sizeof(h.h));
	fh=jh=0;
	register int i,j;
	for(i=1;i<=m;i++)lca(a[i],mid);
	cur=s.h[1];
	while(cur!=-1){
		tmp=s.f[cur];
		nh=0;
    	curs=h.h[tmp.to];
    	while(curs!=-1){
    		now[++nh]=h.f[curs].w;
    		curs=h.f[curs].z;
		}
		fxt=0;
		sort(now+1,now+nh+1);
		if(!flag[tmp.to]&&dfs2(tmp.to,1)){
			fxt=1;
			if(!nh||(nh&&now[1]>=tmp.w))fin[++fh]=tmp.w,fxt=0;
		}
		for(i=1+fxt;i<=nh;i++) if(now[i]>0)jun[++jh]=now[i];
		cur=tmp.z;
    }
    sort(fin+1,fin+fh+1);
    sort(jun+1,jun+jh+1);
    i=j=1;
    while(i!=fh+1&&j!=jh+1){
    	if(fin[i]<=jun[j]) i++,j++;
    	else j++;
	}
	//printf("\n");
	if(i==fh+1) return 1;
	else return 0;
}
int main(){
//	freopen("1.in","r",stdin);
	memset(s.h,-1,sizeof(s.h));
	register int i,j;
	scanf("%d",&n);
	for(i=1;i<=n;i++) lg[i]=lg[i-1]+(1<<lg[i-1]==i);
	for(i=1;i<n;i++) scanf("%d%d%lld",&x,&y,&z),s.add(x,y,z),s.add(y,x,z),anss+=z;
	dfs(1,0);
	scanf("%d",&m);
	for(i=1;i<=m;i++) scanf("%d",&a[i]);
	l=-1;r=anss+1;
	while(l+1<r){
		mid=(l+r)>>1;
		//printf("%d\n",mid);
		if(check(mid)) r=mid;
		else l=mid;
	}
	if(l==anss) printf("-1\n");
	else printf("%lld\n",r);
}
posted @ 2020-08-16 11:41  275307894a  阅读(45)  评论(0)    收藏  举报
浏览器标题切换
浏览器标题切换end