牛客网 牛客练习赛7 D. 珂朵莉的无向图(多源BFS)

题目链接  Problem D

比赛的时候完全想不到

直接对给定的这些点做多源$BFS$,把给定的这些点全都压到队列里,然后一个个做。

最后统计被访问的点的个数即可。

#include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b)	for (int i(a); i <= (b); ++i)
#define dec(i, a, b)	for (int i(a); i >= (b); --i)
#define MP		make_pair
#define fi		first
#define se		second

const int N = 5010;

int d[N], vis[N];
int n, m, q, t, s;
int ret = 0;
queue <int> Q;
vector <int> v[N];

void bfs(){
	int x = Q.front();
	Q.pop();
	++ret;
	if (d[x] == s) return;
	for (auto u : v[x]){
		if (vis[u]) continue;
		if (d[u] > d[x] + 1){
			d[u] = d[x] + 1;
			Q.push(u);
			vis[u] = 1;
		}
	}
}

int main(){

	scanf("%d%d%d", &n, &m, &q);
	while (m--){
		int x, y;
		scanf("%d%d", &x, &y);
		v[x].push_back(y);
		v[y].push_back(x);
	}

	while (q--){
		ret = 0;
		scanf("%d%d", &t, &s);
		memset(d, 127, sizeof d);
		memset(vis, 0, sizeof vis);
		rep(i, 1, t){
			int x;
			scanf("%d", &x);
			if (vis[x]) continue;
			d[x] = 0;
			Q.push(x);
			vis[x] = true;
		}

		while (!Q.empty()) bfs();
		printf("%d
", ret);
	}

	return 0;
}

  

原文地址:https://www.cnblogs.com/cxhscst2/p/7994697.html