求条
查看原帖
求条
640816
cengzh楼主2025/1/19 10:18
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <iostream>
#include <queue>

using namespace std;

int kk[100005];
int is[100005];
int ans[200005];

struct Node {
    int p;
    Node* nxt;
};

struct BFSNode {
    int point;
    int dis;
};

struct Head {
    Node* nxt;
};

Head p[100005];

Node* ini() {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp->nxt = NULL;
    return tmp;
}

void add(int a, int b) {
    Node* tmp1 = ini();
    Node* tmp2 = ini();

    tmp1->nxt = p[a].nxt;
    tmp1->p = b;
    p[a].nxt = tmp1;

    tmp2->p = a;
    tmp2->nxt = p[b].nxt;
    p[b].nxt = tmp2;
}
/*
9 8 5
1 4 5 6 7
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
*/
void BFS(int x) {
    queue<BFSNode> q;
    q.push({x, 0});

    while (!q.empty()) {
        BFSNode now = q.front();
        q.pop();

        Node* tmp = p[now.point].nxt;
        while (tmp != NULL) {
            if (now.dis + 1 < ans[tmp->p] && tmp->p != x) {
                ans[tmp->p] = now.dis + 1;
                q.push({tmp->p, now.dis + 1});
            }
            if (is[tmp->p] && tmp->p != x)
            {
            	ans[x] = min(ans[x],now.dis+1);
			}
            tmp = tmp->nxt;
        }
    }
}

int main(void) {
    int n, m, k;
    scanf("%d %d %d", &n, &m, &k);

    for (int i = 1; i <= n; i++) {
        ans[i] = INT_MAX;
        p[i].nxt = NULL;
    }
/*
6 6 2
1 5
1 2
2 3
3 4
4 5
5 6
6 2
*/
    for (int i = 0; i < k; i++) {
        scanf("%d", &kk[i]);
        is[kk[i]] = 1;
    }

    for (int i = 0; i < m; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        add(a, b);
    }

    for (int i = 0; i < k; i++) {
        BFS(kk[i]);
    }

    for (int i = 1; i <= n; i++) {
        if (ans[i] == INT_MAX) {
            printf("-1 ");
        } else {
            printf("%d ", ans[i]);
        }
    }

    return 0;
}

思路是从每个商店bfs?

2025/1/19 10:18
加载中...