[置顶] poj3160(Tarjan+Spfa)

方法RT,但是一直wa不知道为何,感觉自己的代码写搓了

今天起来研究了一下,发现错误好多,机智的找到错误,ac

感觉好多人的题解都是dp,我觉得没那么麻烦

首先联通缩点,然后设置一个超级源点,于是只要从超级源点出发找,找到一条离超级源点最长的路径即可(缩点之后的图边是有向边),Spfa变形一下

/*
* this code is made by LinMeiChen
* Problem:
* Type of Problem:
* Thinking:
* Feeling:
*/
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<string>
#include<vector>
#include<queue>
#include<list>
using namespace std;
typedef long long lld;
typedef unsigned int ud;
#define oo 0x3f3f3f3f
#define maxn 30003
#define maxm 150015
struct Edge
{
	int v, next;
}E[maxm],E2[maxm];
int n, tol, num, top, tol2, g_cnt;
int head[maxn], stack[maxn];
int low[maxn], dfn[maxn];
int dis[maxn], mark[maxn];
int id[maxn], q[maxn];
int front, rear;
int value[maxn], va[maxn];
int h[maxn];

void Init()
{
	memset(value, 0, sizeof value);
	memset(mark, 0, sizeof mark);
	memset(head, -1, sizeof head);
	memset(low, 0, sizeof low);
	memset(dfn, 0, sizeof dfn);
	memset(id, 0, sizeof id);
	memset(h, -1, sizeof h);
	tol = tol2 = num = top = g_cnt = 0;
}

void add_edge(int u, int v)
{
	E[tol].v = v;
	E[tol].next = head[u];
	head[u] = tol++;
}

void add_edge2(int u, int v)
{
	E2[tol2].v = v;
	E2[tol2].next = h[u];
	h[u] = tol2++;
}

void Tarjan(int u)
{
	dfn[u] = low[u] = ++g_cnt;
	stack[top++] = u;
	mark[u] = 1;
	for (int i = head[u]; i!=-1; i = E[i].next)
	{
		int v = E[i].v;
		if (!dfn[v])
		{
			Tarjan(v);
			low[u] = min(low[u], low[v]);
		}
		else if (mark[v])
		{
			low[u] = min(low[u], dfn[v]);
		}
	}
	if (low[u] == dfn[u])
	{
		int v;
		num++;
		do
		{
			v = stack[--top];
			mark[v] = 0;
			id[v] = num;
		} while (v != u);
	}
}

void Reach(int s)
{
	for (int i = 0; i < n;i++)
	if (!dfn[i])
		Tarjan(i);
	int u, v;
	for (int i = 0; i < n; i++)
	{
		u = i;
		for (int j = head[u]; j != -1; j = E[j].next)
		{
			int v = E[j].v;
			if (id[u] != id[v])
				add_edge2(id[u], id[v]);
		}
	}
	for (int i = 1; i <= num; i++)
		add_edge2(s, i);
	for (int i = 0; i < n; i++)
	{
		if (va[i]>0)
			value[id[i]] += va[i];
	}
}

void Spfa(int s)
{
	for (int i = 0; i <= num; i++)
	{
		mark[i] = 0;
		dis[i] = 0;
	}
	front = rear = 0;
	q[rear++] = s;
	mark[s] = 1;
	dis[s] = 0;
	while (front < rear)
	{
		int u = q[front++];
		mark[u] = 0;
		for (int i = h[u]; i != -1; i = E2[i].next)
		{
			int v = E2[i].v;
			if (dis[u] + value[v] > dis[v])
			{
				dis[v] = dis[u] + value[v];
				if (!mark[v])
				{
					q[rear++] = v;
					mark[v] = 1;
				}
			}
		}
	}
}

int main()
{
	int m, u, v;
	while (scanf("%d%d", &n, &m) != EOF)
	{
		Init();
		for (int i = 0; i < n; i++)
			scanf("%d", &va[i]);
		for (int i = 1; i <= m; i++)
		{
			scanf("%d%d", &u, &v);
			add_edge(u, v);
		}
		Reach(n + 2);
		Spfa(n + 2);
		int Max = 0;
		for (int i = 1; i <= num; i++)
		{
			Max = max(Max, dis[i]);
		}
		printf("%d\n", Max);
	}
	return 0;
}
/*
4 3
14
21
5
5
0 1
1 0
3 2
*/

你可能感兴趣的:(算法,poj,Tarjan,SPFA)