codeforces-796D-Police Stations-多源bfs

题目链接

题意:给你一棵树,树上的一些点是警察局,现在要求每个点到最近的警察局的距离小于等于d,问你最多能删掉多少边使得这个要求仍然满足

这次cf的D,感觉比C要简单一些啊……好吧,主要C一开始想了个很挫的方法……还是错的……

思路:每个点只要保留到最近的警察局的边就行了,别的可以随便删。所以从每个警察局开始bfs,第一次访问到的点保留走过的边,别的删掉就行。

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
#include<stdio.h>
#include<map>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
struct node
{
int u;
int d;
};
int n,k,d;
int isp[300005];
int edge[300005][3];
vector<int>g[300005];
queue<node>q;
int vis[300005];
map<pair<int,int> ,int>f;
int main()
{
scanf("%d%d%d",&n,&k,&d);
for(int i=1;i<=k;i++)
{
int x;
scanf("%d",&x);
isp[x]=1;
q.push((node){x,0});
vis[x]=1;
}
for(int i=1;i<=n-1;i++)
{
int u,v;
scanf("%d%d",&u,&v);
edge[i][1]=u;
edge[i][2]=v;
g[u].push_back(v);
g[v].push_back(u);
}
int cnt=n-1;
while(!q.empty())
{
node temp=q.front();
q.pop();
int x=temp.u;
int dd=temp.d;
if(dd>=d)continue;
int l=g[x].size();
for(int i=0;i<l;i++)
{
int v=g[x][i];
if(vis[v]==1)continue;
vis[v]=1;
node nn=(node){v,dd+1};
f[make_pair(min(x,v),max(x,v))]=1;
cnt--;
q.push(nn);
}
}
printf("%d\n",cnt);
for(int i=1;i<=n-1;i++)
{
int u=edge[i][1];
int v=edge[i][2];
if(f[make_pair(min(u,v),max(u,v))]==0)printf("%d ",i);
}
return 0;
}