POJ3268 Silver Cow Party SPFA

对图分别建立入边表和出边表,分别求出x到个点的最短路,然后相加求出最大值。
Silver Cow Party

Time Limit: 2000MS

 

Memory Limit: 65536K

Total Submissions: 8756

 

Accepted: 3911

Description

One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤XN). A total ofM (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; roadi requiresTi (1 ≤Ti ≤ 100) units of time to traverse.

Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.

Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?

Input

Line 1: Three space-separated integers, respectively: N, M, and X
Lines 2.. M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.

Output

Line 1: One integer: the maximum of time any one cow must walk.

Sample Input

4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3

Sample Output

10

Hint

Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.
 
#include
#include
#include
#include
#include
#include

using namespace std;

#define MAXN 1010
#define INF 0xFFFFFF
//spfa判断存在负权值的方法,一个点入队n次
struct node
{
	int to;
	int dis;
};
bool in[MAXN];
int s[MAXN];
vector g[2][MAXN];
int n,m,x,dis[MAXN];
//int path[MAXN];
void spfa(int s,int x)
{
	queue q;
	for(int i=1;i<=n;i++)
	{
		dis[i]=INF;
		in[i]=false;
		//path[i]=-1;
	}
	dis[s]=0;
	in[s]=true;
	//path[s]=s;
	q.push(s);
	while(!q.empty())
	{
		int tag=q.front();
		in[tag]=false;
		q.pop();
		for(int i=0;i>x>>y>>d;
		scanf("%d%d%d",&x,&y,&d);
		temp.to=y;
		temp.dis=d;
		g[0][x].push_back(temp);
		temp.to=x;
		g[1][y].push_back(temp);
	}
}

void solve()
{
	int maxs=0;
	spfa(x,0);  //出边表的 SPFA 
	for(int i=1;i<=n;i++)
		s[i]=dis[i];
	spfa(x,1);  //入边表 
	for(int i=1;i<=n;i++)
	{
		s[i]+=dis[i];
		maxs=max(maxs,s[i]);
	}
	printf("%d\n",maxs);
	
}

int main()
{
	while(scanf("%d%d%d",&n,&m,&x)!=EOF)
	{
		init();
		solve();
	}
	return 0;
} 

你可能感兴趣的:(最短路,图论)