本文主要是介绍poj 3268 SPFA,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 18421 | Accepted: 8434 |
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 irequires 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
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
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
题意:
一些牛要从各自的农场到某一个指定农场X,然后再回各自的农场
给出一系列单向边,求当单路程(单向)最短的时候总路程最长
这题看似麻烦,因为全部从X点返回各自农场是一个X到其他所有点的最短路径问题
但是从各自点到X点貌似就是N个点各自的最短路了
但其实可以这样,从所有点到X点就是逆的X点到其他点的过程,只不过走的路径也是反的
那么其实就很简单了,正向建边用于计算从X点返回各自点,而反向建边构成一张新的图
也是计算从X点返回各点的最短路径,其实这些边本来是从各点到X,但是反向建之后就变成了X到各点了
然后就变成简单的一点到多点的最短路
#include<queue>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;#define MAXN 100010
#define INF 0x3f3f3f3fstruct node
{int a,b,c;
}t[MAXN];
struct ways
{int v,w,next;
}path[MAXN];int n,m,x;int top,head[1010];
void add(int u,int v,int w)
{path[top].v=v;path[top].w=w;path[top].next=head[u];head[u]=top++;
}int vis[MAXN],dis[MAXN];
int ans[1010];void SPFA()
{for(int i=1;i<=n;i++){dis[i]=INF;vis[i]=0;}dis[x]=0;vis[x]=1;queue<int>q;q.push(x);while(q.size()){int pos=q.front();q.pop();vis[pos]=0;for(int i=head[pos];i!=-1;i=path[i].next){int t=path[i].v;if(dis[t]>dis[pos]+path[i].w){dis[t]=dis[pos]+path[i].w;if(vis[t]==0){q.push(t);vis[t]=1;}}}}for(int i=1;i<=n;i++)ans[i]+=dis[i];
}int main()
{top=0;//freopen("in.txt","r",stdin);memset(ans,0,sizeof(ans));memset(head,-1,sizeof(head));scanf("%d%d%d",&n,&m,&x);for(int i=0;i<m;i++){scanf("%d%d%d",&t[i].a,&t[i].b,&t[i].c);add(t[i].a,t[i].b,t[i].c);}SPFA();top=0;memset(head,-1,sizeof(head));for(int i=0;i<m;i++){add(t[i].b,t[i].a,t[i].c);}SPFA();int temp=0;for(int i=1;i<=n;i++)temp=temp>ans[i]?temp:ans[i];printf("%d\n",temp);return 0;
}
这篇关于poj 3268 SPFA的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!