洛谷 P1113 杂务 题解

版权声明:随便转载。 https://blog.csdn.net/zhang14369/article/details/80308256

作者:岸芷汀兰

一、题目:

洛谷原题

二、思路:

第一眼看题,立即想到拓扑排序
再看一下标签——“递推”,真没看出和递推有何关系!
言归正传,咳咳。入度为0的点的权值就是它的时间,入读不为0的点的权值是它的所有前驱的权值的最大值加上他的时间,遇到出度为0的点,计算完他的权值后,更新一下答案。(有点贪心的意思。)
上代码。

三、代码:

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>

using namespace std;
inline int read(void) {
    int x = 0, f = 1; char ch = getchar();
    while (ch<'0' || ch>'9') {
        if (ch == '-')f = -1;
        ch = getchar();
    }
    while (ch >= '0'&&ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return f * x;
}

const int maxn = 10005;

int n, ans;

int head[maxn], tot, in[maxn], out[maxn], wei[maxn], cnt[maxn];

queue<int>q;

struct Edge {
    int y, next;
}e[5000005];

inline void connect(int x, int y) {
    e[++tot].y = y; e[tot].next = head[x]; head[x] = tot;
}

int main()
{
    n = read();
    for (register int i = 1; i <= n; i++) {
        int x = read(); wei[x] = read();
        while (233) {
            int y = read();
            if (!y)break;
            out[x]++; in[y]++;
            connect(x, y);
        }
    }
    for (register int i = 1; i <= n; i++) {
        if (!in[i]) {
            q.push(i); cnt[i] = wei[i];
        }
    }
    while (q.size()) {
        int u = q.front(); q.pop();
        for (register int i = head[u]; i; i = e[i].next) {
            int v = e[i].y;
            in[v]--; cnt[v] = max(cnt[v], cnt[u] + wei[v]);
            if (!in[v]) {
                if (!out[v])ans = max(ans, cnt[v]);
                else q.push(v);
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhang14369/article/details/80308256