D - Test for Job (POJ - 3249)

Posted Alpacaddhh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D - Test for Job (POJ - 3249)相关的知识,希望对你有一定的参考价值。

- 题目大意

    给你一个图,求一条起点(入度为0)到终点(出度为0)的路。满足全部点的val之和最大。

- 解题思路

   先用数组记录入度为0和出度为0的点,然后利用记忆化搜索来解决。

- 代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f;
const int N = 1e6 + 10;
long long cnt,sum;
long long d[N], head[N], num[N], vis[N];
struct egde {
	long long u, v, w;
}e[N];

long long dfs(long long u)
{
	if (d[u])
		return d[u];
	long long MAX = -INF;
	for (long long i = head[u]; ~i; i = e[i].w)
	{
		long long v = e[i].v;
		MAX = max(MAX, dfs(v));
	}
	if (MAX== -INF)
		 MAX = 0;
		d[u] =MAX+ num[u];
		return d[u];
}

void addEdge(long long u, long long v)
{
	e[cnt].v = v;
	e[cnt].u = u;
	e[cnt].w = head[u];
	head[u] = cnt++;
}

int main()
{
	long long n, m, a, b;
	while (scanf_s("%lld%lld", &n, &m) != EOF)
	{
		for (long long i = 1; i <= n; i++)
			scanf_s("%lld", &num[i]);
		cnt = 0;
		memset(head, -1, sizeof(head));
		memset(vis, 0, sizeof(head));
		memset(d, 0, sizeof(d));
		for (long long i = 0; i < m; i++)
		{
			scanf_s("%lld%lld", &a, &b);
			addEdge(a, b);
			vis[b]++;
		}
		sum = -INF;
		for (long long i = 1; i <= n; i++)
		{
			if (vis[i] == 0)
				sum = max(sum, dfs(i));
		}
		printf("%lld\n", sum);
	}
	return 0;
}

  

以上是关于D - Test for Job (POJ - 3249)的主要内容,如果未能解决你的问题,请参考以下文章

poj 3249 Test for Job (DAG最长路 记忆化搜索解决)

POJ 3249 Test for Job (dfs + dp)

POJ 3249 Test for Job (拓扑排序+DP)

[POJ3249]Test for Job [拓扑排序+DAG上的最长路径]

Test for Job 图上的动态规划(DAG)

HDU 3249 Test for job (有向无环图上的最长路,DP)