传送门
Problem Description
1.校园网主干是由N个节点(编号1..N)组成,这些节点之间有一些单向的网路连接。若存在一条网路连接(u,v)链接了节点u和节点v,则节点u可以向节点v发送信息,但是节点v不能通过该链接向节点u发送信息。
2.在刚感染病毒时,校园网立刻切断了一些网络链接,恰好使得剩下网络连接不存在环,避免了节点被反复感染。也就是说从节点i扩散出的病毒,一定不会再回到节点i。
3.当1个病毒感染了节点后,它并不会检查这个节点是否被感染,而是直接将自身的拷贝向所有邻居节点发送,它自身则会留在当前节点。所以一个节点有可能存在多个病毒。 现在已经知道黑客在一开始在K个节点上分别投放了一个病毒。
Input
第1行:3个整数N,M,K,1≤K≤N≤100,000,1≤M≤500,000
第2行:K个整数A[i],A[i]表示黑客在节点A[i]上放了1个病毒。1≤A[i]≤N
第3..M+2行:每行2个整数 u,v,表示存在一条从节点u到节点v的网络链接。数据保证为无环图。1≤u,v≤N
Output
第1行:1个整数,表示最后整个网络的病毒数量 MOD 142857
Sample Input
4 4 1
1
1 2
1 3
2 3
3 4
Sample Output
6
Solution
在拓扑排序问题上加了一些改变,需要对问题进行分析,才能在找到求解方法,即在拓扑排序上做了一些改变。
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
int n, m, k, x, y, ans;
const int maxn = 100005;
const int mo = 142857;
//邻接矩阵
vector<int> vec[maxn];
int InDeg[maxn], num[maxn];
queue<int> q;
void topsort() {
//清空队列
while (!q.empty())
q.pop();
//入度为0的入队
for (int i = 1; i <= n; i++)
if (!InDeg[i]) q.push(i);
//广度优先遍历
while (!q.empty()) {
int now = q.front();
q.pop();
for (int i = 0; i < (vec[now].size()); i++) {
if (--InDeg[vec[now][i]] == 0) q.push(vec[now][i]);
//下一个节点的病毒数 = 其本身病毒 + 前驱节点入度数
num[vec[now][i]] = (num[vec[now][i]] + num[now]) % mo;
}
}
}
int main() {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) vec[i].clear();
memset(InDeg, 0, sizeof(InDeg));
memset(num, 0, sizeof(num));
while (k--) {
cin >> x;
num[x]++;
}
//记录初始数据
for (int i = 0; i < m; i++) {
cin >> x >> y;
vec[x].push_back(y);
InDeg[y]++;
}
topsort();
ans = 0;
for (int i = 1; i <= n; i++) {
ans = (ans + num[i]) % mo;
}
cout << ans << endl;
return 0;
}