【[ARC063C] Integers on a Tree】

题目链接

对于最小的点,与它相连的没填的点中,都赋值为这个点点权+1。

这样子贪心就算旁边的点必然会比这个点大,所以+1是没错的。

最后再遍历所有边检验答案合法性。

Code

// Problem: AT2148 [ARC063C] 木と整数 / Integers on a Tree
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/AT2148
// Memory Limit: 250 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
//#define int long long
inline int read(){int 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<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define mo
//#define M
#define N 100010
struct node
{
	int x, id; 
	bool operator <(const node &A) const
	{
		return x>A.x; 
	}
}t, tt; 
struct Node
{
	int x, y, n; 
}d[N*2]; 
int n, m, i, j, k; 
int h[N], u, v, a[N]; 
priority_queue<node>q; 

void cun(int x, int y)
{
	d[++k].x=x; d[k].y=y; 
	d[k].n=h[x]; h[x]=k; 
}

signed main()
{
//	freopen("tiaoshi.in","r",stdin);
//	freopen("tiaoshi.out","w",stdout);
	memset(a, 0x3f, sizeof(a)); 
	n=read(); 
	for(i=1; i<n; ++i)
	{
		u=read(); v=read(); 
		cun(u, v); cun(v, u); 
	}
	m=read(); 
	for(i=1; i<=m; ++i) 
	{
		k=read(); 
		a[k]=read();
		t.x=a[k]; t.id=k; 
		q.push(t); 
	}
	while(!q.empty())
	{
		t=q.top(); q.pop(); 
		for(int g=h[t.id]; g; g=d[g].n)
		{
			int y=d[g].y; 
			if(a[y]!=a[0]) continue; 
			tt.x=a[y]=a[t.id]+1; 
			tt.id=y; 
			q.push(tt); 
		}
	}
	for(i=1; i<n; ++i)
		if(abs(a[d[i*2].x]-a[d[i*2].y])!=1) return printf("No"), 0; 
	printf("Yes\n"); 
	for(i=1; i<=n; ++i) printf("%lld\n", a[i]); 
	return 0;
}

posted @ 2021-12-02 16:11  zhangtingxi  阅读(46)  评论(0编辑  收藏  举报