AcWing 477. 神经网络
作者:互联网
解题思路:
- DAG求拓扑序
- 利用拓扑序列,根据题意做递推
#include <bits/stdc++.h>
using namespace std;
const int N = 110, M = N * N / 2;
int n, m;
int f[N], din[N], dout[N];
//邻接表
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
vector<int> path;
void topsort() {
queue<int> q;
for (int i = 1; i <= n; i++)
if (!din[i]) q.push(i);
while (q.size()) {
int t = q.front();
q.pop();
path.push_back(t);
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (--din[j] == 0)
q.push(j);
}
}
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
int a, b;
//最初状态,阈值
cin >> a >> b;
if (!a)
f[i] -= b;
else
f[i] += a;
}
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
dout[a]++, din[b]++; //需要知道哪些是终点,就记录了出度
}
//拓扑序
topsort();
//遍历拓扑序列
for (int i = 0; i < path.size(); i++) {
int j = path[i];
if (f[j] > 0)
for (int k = h[j]; ~k; k = ne[k])
f[e[k]] += f[j] * w[k];
}
bool flag = true;
for (int i = 1; i <= n; i++)
if (!dout[i] && f[i] > 0) {
printf("%d %d\n", i, f[i]);
flag = false;
}
if (flag) puts("NULL");
return 0;
}
标签:idx,int,拓扑,ne,++,神经网络,477,path,AcWing 来源: https://www.cnblogs.com/littlehb/p/16122271.html