gym-103708B Building 5G antennas


Building 5G antennas

dfs 剪枝

要字典序最小,显然第一个点就是 /(1/),后面考虑走 /(k/) 步后能到达的点集中选一个字典序最小的,重复该过程

考虑 /(set[i][j]/) 表示第 /(i/) 号点当前能走 /(j/) 步所包含的点的集合,我们可以发现对于相同的点,如果 /(j_1 > j_2/),显然有 /(set[i][j_1]/) 包含 /(set[i][j_2]/) 的情况

因此之前如果访问到一个点,且步数比当前搜到这个点的步数还大,则说明当前走下去想要访问的点之前已经被访问过了,直接剪枝

这样每个点最多被访问 /(k/) 次

时间复杂度是 /(O(nk)/)

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
#include <functional>
using namespace std;
const int maxn = 1e5 + 10;
vector<int>gra[maxn];
priority_queue<int, vector<int>, greater<int> >q;
int num[maxn];

void dfs(int now, int pre, int cnt)
{
    if(cnt == -1) return;
    if(num[now] >= cnt) return;
    if(num[now] == -1) q.push(now);
    num[now] = cnt;
    for(int nex : gra[now])
    {
        if(nex == pre) continue;
        dfs(nex, now, cnt - 1);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, k;
    cin >> n >> k;
    for(int i=1; i<n; i++)
    {
        int a, b;
        cin >> a >> b;
        gra[a].push_back(b);
        gra[b].push_back(a);
    }
    for(int i=0; i<=n; i++) num[i] = -1;
    q.push(1);
    vector<int>ans;
    while(q.size())
    {
        int now = q.top();
        q.pop();
        ans.push_back(now);
        num[now] = 0;
        dfs(now, now, k);
    }
    for(int i=0; i<ans.size(); i++)
    {
        if(i) cout << " ";
        cout << ans[i];
    }
    cout << endl;
    return 0;
}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282773.html

(0)
上一篇 2022年8月29日
下一篇 2022年8月29日

相关推荐

发表回复

登录后才能评论