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
大致题意
第一行 n , m , x,n个点,m条单向道,每个点去x再回到自己的点,问所有点去完回来后中的最大值
具体思路
dijkstra的优点就是一个点到所有点的最短距离,因此可以用dijkstra求出各个点从x回来的花费存储到ans数组中,那对于去的时候怎么办呢,其实也是一样的,从x开始,把所有的单向道反过来,就可以用反方向dijkstra求出所有点到x的花费,在这里开了个结构体,并且在循环ans数组存储的时候把vector数组全部初始化,以便于第二次使用
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
vector<pair<int,int> >line[1005];
int n,dis[1005],flag[1005];
struct node
{
int from,to,cost;
}value[100005];
void dijkstra(int from)
{
memset(flag,0,sizeof(flag));
fill(dis,dis+1005,0x7fffffff);
dis[from]=0;
flag[from]=1;
queue<int>dui;
dui.push(from);
while (!dui.empty())
{
int now=dui.front();
dui.pop();
flag[now]=0;
for (int i=0;i<line[now].size();i++)
{
if (dis[now]+line[now][i].second<dis[line[now][i].first])
{
dis[line[now][i].first]=dis[now]+line[now][i].second;
if (flag[line[now][i].first]==0)
{
flag[line[now][i].first]=1;
dui.push(line[now][i].first);
}
}
}
}
}
int main()
{
int ans[1005];
int m,n,x;
scanf("%d %d %d",&n,&m,&x);
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&value[i].from,&value[i].to,&value[i].cost);
line[value[i].from].push_back(make_pair(value[i].to,value[i].cost));
}
dijkstra(x);
for (int i=1;i<=n;i++)
{
line[i].clear();
ans[i]=dis[i];
}
for(int i=0;i<m;i++)
{
line[value[i].to].push_back(make_pair(value[i].from,value[i].cost));
}
dijkstra(x);
int maxans=0;
for (int i=1;i<=n;i++)
{
ans[i]+=dis[i];
maxans=max(ans[i],maxans);
}
printf("%d\n",maxans);
return 0;
}