POJ3268 Silver Cow Party(多次Dijkstra)

题目链接

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 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (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

思路

对于每头牛而言,从起点到终点的最短路径可以通过Dijkstra求出,返回的最短路径只需要将起点和终点对调,最后输出记录下的最短路径中的最大值即可。

代码部分

#include<queue>
#include<math.h>
#include<stdio.h>
#include<iostream>
using namespace std;
const int maxn=1e3+5;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
struct node
{
    
    
	int v,w;
	node(int v,int w):v(v),w(w){
    
    }
};
struct Node
{
    
    
    int v,w;
    Node(int v,int w):v(v),w(w){
    
    }
    friend bool operator < (const Node a,const Node b)
    {
    
    
        return a.w > b.w;
    }
};
vector<node> a[maxn];
priority_queue<Node> que;
bool vis[maxn];
int n;
int dis[maxn];
void dij(int s)
{
    
    
	memset(dis,inf,sizeof(dis));
	memset(vis,false,sizeof(vis));
	dis[s]=0;
	que.push(Node(s,0));
	while(!que.empty())
	{
    
    
		int u=que.top().v;
		que.pop();
		vis[u]=true;
		for(int i=0;i<a[u].size();i++)
		{
    
    
			int v=a[u][i].v;int w=a[u][i].w;
			if(!vis[v]&&dis[v]>dis[u]+w)
			{
    
    
				dis[v]=dis[u]+w;
				que.push(Node(v,dis[v]));
			}
		}
	}
}
int main()
{
    
    
	int m,x,u,v,w,ans;
	ans=-1;
	scanf("%d%d%d",&n,&m,&x);
	for(int i=0;i<m;i++)
	{
    
    
		scanf("%d%d%d",&u,&v,&w);
		u--;v--;
		a[u].push_back(node(v,w));
	}
	for(int i=0;i<n;i++)
	{
    
    
		int sum=0;
		dij(i);
		sum+=dis[x-1];
		dij(x-1);
		sum+=dis[i];
		ans=max(ans,sum);
	}
	printf("%d\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WTMDNM_/article/details/107680174