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;
}
posted @ 2022-04-09 15:47  糖豆爸爸  阅读(65)  评论(0编辑  收藏  举报
Live2D