题解 洛谷 Luogu P1038 [NOIP 2003 提高组] 神经网络 拓扑排序 C++

题目

传送门

P1038 [NOIP 2003 提高组] 神经网络 - 洛谷 | 计算机科学教育新生态https://www.luogu.com.cn/problem/P1038https://www.luogu.com.cn/problem/P1038https://www.luogu.com.cn/problem/P1038https://www.luogu.com.cn/problem/P1038https://www.luogu.com.cn/problem/P1038https://www.luogu.com.cn/problem/P1038

思路

为什么用拓扑排序?

拓扑排序的主要应用之一就是基于 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值