Codeforces - Police Stations

本文详细解析了Codeforces平台上的PoliceStations题目,介绍了如何通过广度优先搜索(BFS)找到必经边,从而解决警察局位置优化问题。代码使用C++实现,展示了完整的算法流程和数据结构设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:Codeforces - Police Stations


我们首先找到必须边,然后问题就解决了。

所以怎么找必须边呢?

每个点肯定是到最近的警察局,又因为两点之间距离都是1,所以我们从警局开始bfs,找到必须边即可。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=3e5+10,M=N<<1;
int n,k,d,vis[N],p[N],mark[N],cnt;
int head[N],nex[M],to[M],id[M],tot;
inline void add(int a,int b,int c){
	to[++tot]=b; nex[tot]=head[a]; id[tot]=c; head[a]=tot;
}
void bfs(){
	queue<int> q;	for(int i=1;i<=k;i++)	vis[p[i]]=1,q.push(p[i]);
	while(q.size()){
		int u=q.front();	q.pop();
		for(int i=head[u];i;i=nex[i]){
			if(!vis[to[i]])	q.push(to[i]),vis[to[i]]=1,mark[id[i]]=1;
		}
	}
}
signed main(){
	cin>>n>>k>>d;
	for(int i=1;i<=k;i++)	scanf("%d",&p[i]);
	for(int i=1,a,b;i<n;i++)	scanf("%d %d",&a,&b),add(a,b,i),add(b,a,i);
	bfs();
	for(int i=1;i<n;i++)	cnt+=mark[i]==0;
	cout<<cnt<<endl;
	for(int i=1;i<n;i++)	if(!mark[i])	printf("%d ",i);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值