跳到正文

个人记录

P1113 杂务 拓扑排序入门

YZL11111约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年8月10日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

题目链接:https://www.luogu.org/problem/P1113

【题目描述】

John的农场在给奶牛挤奶前有很多杂务要完成,每一项杂务都需要一定的时间来完成它。比如:他们要将奶牛集合起来,将他们赶进牛棚,为奶牛清洗乳房以及一些其它工作。尽早将所有杂务完成是必要的,因为这样才有更多时间挤出更多的牛奶。当然,有些杂务必须在另一些杂务完成的情况下才能进行。比如:只有将奶牛赶进牛棚才能开始为它清洗乳房,还有在未给奶牛清洗乳房之前不能挤奶。我们把这些工作称为完成本项工作的准备工作。至少有一项杂务不要求有准备工作,这个可以最早着手完成的工作,标记为杂务1。John有需要完成的nn个杂务的清单,并且这份清单是有一定顺序的,杂务k(k>1)的准备工作只可能在杂务1至k-1中。

写一个程序从1到n读入每个杂务的工作说明。计算出所有杂务都被完成的最短时间。当然互相没有关系的杂务可以同时工作,并且,你可以假定John的农场有足够多的工人来同时完成任意多项任务。

【输入格式】

第1行:一个整数n,必须完成的杂务的数目(3≤n≤10,000);

第22至(n+1)行: 共有n行,每行有一些用1个空格隔开的整数,分别表示:

  • 工作序号(1至n,在输入文件中是有序的);

  • 完成工作所需要的时间len(1≤len≤100);

  • 一些必须完成的准备工作,总数不超过100个,由一个数字0结束。有些杂务没有需要准备的工作只描述一个单独的0,整个输入文件中不会出现多余的空格。

【输出格式】

一个整数,表示完成所有杂务所需的最短时间。

【解题思路】

拓扑排序裸题,但此题也可以不使用拓扑排序

【AC代码】

C++
//拓扑排序做法
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10000 + 10;
bool G[maxn][maxn];
int t[maxn];
int c[maxn];
int mx[maxn];
int n, ans;
void TopoSort()
{
	queue<int> que;
	for (int i = 1; i <= n; i++)
	{
		if (c[i] == 0)
		{
			que.push(i);
			mx[i] = t[i];
		}
	}
	while (!que.empty())
	{
		int u = que.front();
		que.pop();
		for (int i = 1; i <= n; i++)
		{
			if (G[i][u])
			{
				c[i]--;
				if (c[i] == 0)
				{
					que.push(i);
				}
				mx[i] = max(mx[i], mx[u] + t[i]);
				ans = max(mx[i], ans);
			}
		}
	}
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%*d");
		scanf("%d", &t[i]);
		int x;
		while (~scanf("%d", &x))
		{
			if (x == 0)
				break;
			c[i]++;
			G[i][x] = true;
		}
	}
	TopoSort();
	printf("%d\n", ans);
	return 0;
}
C++
//非拓扑排序做法
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10000 + 10;
int ans[maxn];
int main()
{
	int n;
	scanf("%d", &n);
	int Max = 0;
	for (int i = 1; i <= n; i++)
	{
		scanf("%*d");
		int w;
		scanf("%d", &w);
		int x;
		int t = 0;
		while (~scanf("%d", &x))
		{
			if (x == 0)
				break;
			t = max(t, ans[x]);
		}
		ans[i] = t + w;
		Max = max(ans[i], Max);
	}
	printf("%d\n", Max);
	return 0;
}
原文