Loading

AtCoder-abc254_e Small d and k

Small d and k

bfs

题目给出了限定:每个点的度最多为 3,并且提问的距离也最多为 3

所以直接 bfs 搜索,然后存一下访问的点,回退状态的时候就不用整个 vis 置为 0

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;
vector<int>gra[maxn];
int vis[maxn];

int bfs(int n, int k)
{
    int ans = 0;
    queue<pii>q;
    vector<int>v;
    q.push({n, 0});
    while(q.size())
    {
        pii now = q.front();
        q.pop();
        if(vis[now.first]) continue;
        int u = now.first;
        ans += u;
        v.push_back(u);
        vis[u] = 1;
        if(now.second == k) continue;
        for(int i=0; i<gra[u].size(); i++)
        {
            int nex = gra[u][i];
            q.push({nex, now.second + 1});
        }
    }
    for(int i=0; i<v.size(); i++)
        vis[v[i]] = 0;
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, m;
    cin >> n >> m;
    for(int i=0; i<m; i++)
    {
        int x, y;
        cin >> x >> y;
        gra[x].push_back(y);
        gra[y].push_back(x);
    }
    int q;
    cin >> q;
    while(q--)
    {
        int x, k;
        cin >> x >> k;
        cout << bfs(x, k) << endl;
    }

    return 0;
}
posted @ 2022-06-07 16:59  dgsvygd  阅读(27)  评论(0编辑  收藏  举报