这
现在有
请问对于每一次事件,有多少人最终会听到这个流言?
第一行正整数。
接下来接下来一行行,每行两个数字
,表示初始的一对朋友关系,朋友关系不会重复给出
个数字,每个数字为
或者
,第
个数字表示第
个人属于第一种人/第二种人。
接下来一行个整数,每个整数代表一次事件中最初听到的流言的人。
对于每个事件,输出一行一个整数,代表受影响的总人数
5 5 5 1 2 2 3 3 4 4 5 1 5 1 2 1 1 2 1 2 3 4 5
3 1 4 4 1
第一次听到流言的人为,第二、五次仅有初始时听到流言的人听到了,第三、四次是
6 7 5 1 2 1 4 1 6 4 6 3 5 1 5 2 6 1 2 1 1 1 2 1 2 3 5 6
6 1 6 6 1
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
int cnt[N];
bool spread[N], st[N];
vector<int> g[N];
int bfs(int x) {
if (!spread[x]) return 1;
memset(st, false, (n + 1)*sizeof(bool));
queue<int> q;
q.push(x);
st[x] = true;
int res = 1;
while (!q.empty()) {
int t = q.front();
q.pop();
if (spread[t]) {
for (int v : g[t]) {
if (!st[v]) {
st[v] = true;
res++;
q.push(v);
}
}
}
}
// 批量赋值:同一连通块的类型1节点,后续查询直接复用
memset(st, false, (n + 1)*sizeof(bool));
q.push(x);
st[x] = true;
while (!q.empty()) {
int t = q.front();
q.pop();
cnt[t] = res;
for (int v : g[t]) {
if (!st[v] && spread[v]) {
st[v] = true;
q.push(v);
}
}
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int m, Q, u, v, x;
cin >> n >> m >> Q;
for (int i = 0; i < m; i++) {
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
// 读类型 + 初始化cnt
for (int i = 1; i <= n; i++) {
cin >> x;
spread[i] = (x == 1);
if (!spread[i]) cnt[i] = 1;
}
// 按需计算:只处理查询的节点
while (Q--) {
cin >> x;
if (cnt[x] == 0) {
cnt[x] = bfs(x);
}
cout << cnt[x] << endl;
}
return 0;
}