Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 21544 | Accepted: 9834 |
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到每个点的最短路,和每个点到x的最短路,之和最小值。
做了几道最短路的题,这个代码我终于一遍过了,有进步;
AC代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<string>
#define LL long long
using namespace std;
const int mod = 1e7+7;
const int inf = 0x3f3f3f3f;
const int maxn = 1e6 +10;
int n,m,x,a,b,c,nn,point,sum,ans;
int ma[1005][1005];//两点的距离
int dis[1005];//从i点去x点的最短距离
int kis[1005];//从x点回到i点最短距离
int vis[1005];//是否已经更新为最小值
int main()
{
while(~scanf("%d%d%d",&n,&m,&x))
{
memset(ma,inf,sizeof(ma));
for(int i=1;i<=n;i++)
ma[i][i]=0;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&c);
ma[a][b]=c;
}
for(int i=1;i<=n;i++)
{
dis[i]=ma[i][x];//i到x
kis[i]=ma[x][i];//x到i
}
memset(vis,0,sizeof(vis));
nn=n;
while(nn--)
{
sum=inf,point=-1;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&dis[i]<sum)
{
sum=dis[i];
point=i;
}
}
if(point!=-1)
{
vis[point ]=1;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&dis[point]+ma[i][point]<dis[i])
dis[i]=dis[point]+ma[i][point];
}
}
}
memset(vis,0,sizeof(vis));
nn=n;
while(nn--)
{
sum=inf,point=-1;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&kis[i]<sum)
{
sum=kis[i];
point=i;
}
}
if(point!=-1)
{
vis[point ]=1;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&kis[point]+ma[point][i]<kis[i])
kis[i]=kis[point]+ma[point][i];
}
}
}
ans=0;
for(int i=1;i<=n;i++)
if(kis[i]+dis[i]>ans)
ans=kis[i]+dis[i];
printf("%d\n",ans);
}
}