| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 13006 | Accepted: 5824 |
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
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再回来的最短距离的最大值。
思路:练习下spfa吧。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
struct node
{
int y,w,next;
}e[100010];
int n,m,h[1010],d[1010],x[100010],y[100010],w[100010],tot,ans,f[1010];
bool vis[1010];
queue<int> qu;
void ins(int x,int y,int w)
{
e[++tot].y=y;
e[tot].w=w;
e[tot].next=h[x];
h[x]=tot;
}
void spfa(int s)
{
int i,j,k,x,y;
qu.push(s);
memset(vis,0,sizeof(vis));
for(i=1;i<=n;i++)
d[i]=1000000000;
d[s]=0;
vis[s]=true;
while(!qu.empty())
{
x=qu.front();
qu.pop();
for(i=h[x];i;i=e[i].next)
{
y=e[i].y;
if(d[x]+e[i].w<d[y])
{
d[y]=d[x]+e[i].w;
if(!vis[y])
{
vis[y]=1;
qu.push(y);
}
}
}
vis[x]=0;
}
}
int main()
{
int i,j,k;
scanf("%d%d%d",&n,&m,&k);
ans=0;
tot=0;
memset(h,0,sizeof(h));
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x[i],&y[i],&w[i]);
ins(x[i],y[i],w[i]);
}
spfa(k);
for(i=1;i<=n;i++)
f[i]+=d[i];
tot=0;
memset(h,0,sizeof(h));
for(i=1;i<=m;i++)
ins(y[i],x[i],w[i]);
spfa(k);
for(i=1;i<=n;i++)
{
f[i]+=d[i];
ans=max(ans,f[i]);
}
printf("%d\n",ans);
}

本文详细介绍了使用SPFA算法求解有向图中每只牛从农场到特定农场参加聚会并返回的最短路径,并通过实例展示了算法的应用。重点在于理解SPFA算法的工作原理和其在解决实际问题中的优势。
349

被折叠的 条评论
为什么被折叠?



