AtCoder Beginner Contest 254 - E - Small d and k 题解

E - Small d and k

这题向我们询问若干次到某个点 \(x_i\) 的距离不超过 \(k\) 的点的下标的和。

有个显著特点,每个点的度数不超过3,我们要考虑的点到 \(x_i\) 的距离不超过3。

于是乎对于每个 \(x_i\),需要计算的点的个数不超过\(1 + 3 + 3^2 + 3^3 = 40\)

所以我们可以放心大胆地对每个点进行\(BFS\)\(DFS\)

有两位大佬使用了\(DFS\)

https://www.cnblogs.com/zengzk/p/16343256.html

https://www.eriktse.com/algorithm/716.html

这里我使用\(BFS\),由于队列中的点到 \(x_i\) 的距离是单调增加的,所以一但遇到距离等于 \(k\) 的点,就可以跳过。

另外这题有两个坑点:

  1. 链式前向星要开得比\(1.5 \times 10^5\)大,而且大得多,这里我也不太明白为什么(否则会\(RE\)) ==
  2. 不能在\(BFS\)的代码中,每次用memset(d, -1, sizeof d)来初始化\(d\)数组,会\(TLE\) (。因为memset的复杂度接近\(\text{O(n)}\),这里的询问次数比较多,故不能用。

这题的特点可能是搜索有深度限制,要着重理解。

代码/Code

// Problem: E - Small d and k
// Contest: AtCoder - AtCoder Beginner Contest 254
// URL: https://atcoder.jp/contests/abc254/tasks/abc254_e
// Memory kit: 1024 MB
// Time kit: 3500 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 1500010;

int n, m, Q;
int h[N], e[N], ne[N], idx;
// now是节点序号,i是now的id,ne[i]是i的下一个点的id
// e[i]是id对应的节点编号
// 此部分学习自AcWing

void add(int a, int b){	// a to b
	e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ; 
}

vector<int> d(N,-1);
int bfs(int node, int k){
	queue<int> q;
	int res = 0;	
	
	q.push(node);
	d[node] = 0;
	vector<int> vs;
	
	while (q.size()){
		int now = q.front();
		q.pop();
		vs.push_back(now);
		if (d[now] == k) continue;
		
		for (int i = h[now]; i != -1; i = ne[i]){
			
			int j = e[i];	
			if (d[j] == -1){
				d[j] = d[now] + 1;
				q.push(j);
			}
		}
	}
	
	for(int i : vs){
		res += i;
		d[i] = -1;
	}
	return res;
}

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
	cin >> n >> m;
	memset(h, -1, sizeof h);
	
	int a, b;
	while (m -- ){
		cin >> a >> b;
		add(a, b);
		add(b, a);
	}
	
	cin >> Q;
	
	int node, k, ans;
	while (Q -- ){
		cin >> node >> k;
		ans = bfs(node, k);
		cout << ans << endl;
	}
	
    return 0;
}

posted @ 2022-06-06 20:50  tsrigo  阅读(83)  评论(0编辑  收藏  举报