本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15633812.html

题目链接

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

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

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

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// 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;
}