题目
传送门
思路
为什么用拓扑排序?
拓扑排序的主要应用之一就是基于 DAG (有向无环图) 的信息传递,这也是一种动态规划
本题的话,就是按拓扑序列传递 c[x] * w
具体地说,c[y] += c[x] * w (边的方向为 x >> y),累加之后减去阈值 u
题目要求分层,所以我们要逐层操作
什么是拓扑排序,怎么求拓扑排序,是很基础的内容,此处不赘述了
坑点
1.输入层不用减去 u,即输入层的 u 完全没用
2.神经元 x 处于兴奋状态,即 c[x] > 0 时,信息才会传递到 y
代码
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
typedef pair<int, int> PII;
constexpr int N = 101;
vector<PII> to[N], ans;
int from[N], n, p, c[N], u[N], q[N], head, tail = -1;
void toposort()
{
for (int i = 1; i <= n; ++i)
if (from[i] == 0)
q[++tail] = i;
while (head <= tail)
{
int sz = tail - head + 1;
for (int i = 0; i < sz; ++i) //逐层操作,一次性出队一整层
{
int x = q[head++];
if (tail == n - 1) //到最后一层了,计入答案
{
if (c[x] > 0) ans.emplace_back(x, c[x]);
continue;
}
for (auto& z : to[x])
{
int X = z.first, w = z.second;
if (c[x] > 0) c[X] += c[x] * w; //只有处于兴奋状态的神经元会传递信息
if (--from[X] == 0)
{
q[++tail] = X;
c[X] -= u[X]; //写在这里就只让新入队的节点减掉阈值,不会让输入层减掉阈值
}
}
}
}
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> p;
for (int i = 1; i <= n; ++i) cin >> c[i] >> u[i];
while (p--)
{
int x, y, w;
cin >> x >> y >> w;
to[x].emplace_back(y, w);
++from[y];
}
toposort();
if (ans.empty()) { cout << "NULL"; return 0; }
sort(ans.begin(), ans.end()); //答案要求有序
for (auto& z : ans)
cout << z.first << ' ' << z.second << '\n';
return 0;
}