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
所有牛去找一头牛开会,求到目标再回到自己原来的地方用时最长的牛的时间。
dijkstra
求出所有点到目标的最短距离。在求出目标点到各点的最短距离。
得出最优解。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <climits>
using namespace std;
const int N = 1005;
int a[N][N];
int n,e,x;
int mindis1[N],mindis2[N];
bool vis1[N],vis2[N];
void init()
{
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[i][j] = -1;
}
void dijkstra(int s)
{
int pos1,pos2,te1,te2,tm1,tm2;
for (int i = 0; i < n; ++i)
{
vis1[i]=vis2[i]=false;
mindis1[i]=mindis2[i]=999999;
}
mindis1[s]=mindis2[s]=0;
vis1[s]=vis2[s]=true;
pos1=pos2=s;
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < n; ++j)
{
if (!vis1[j] && a[pos1][j] != -1 && mindis1[pos1] + a[pos1][j] < mindis1[j])
{
mindis1[j] = mindis1[pos1] +a[pos1][j];
}
if (!vis2[j] && a[j][pos2] != -1 && mindis2[pos2] + a[j][pos2] < mindis2[j])
{
mindis2[j] = mindis2[pos2] + a[j][pos2];
}
}
tm1 = tm2 = 999999;
for (int j = 0; j < n; ++j)
{
if (!vis1[j] && mindis1[j] < tm1)
{
tm1 = mindis1[j];
te1 = j;
}
if (!vis2[j] && mindis2[j] < tm2)
{
tm2 = mindis2[j];
te2 = j;
}
}
vis1[te1] = vis2[te2] = true;
pos1 = te1;
pos2 = te2;
}
}
int main()
{
int beg, end, dis;
scanf("%d%d%d", &n, &e, &x);
init();
for (int i = 0; i < e; ++i)
{
scanf("%d%d%d", &beg, &end, &dis);
--beg;
--end;
a[beg][end] = dis;
}
dijkstra(--x);
int ans = 0;
for (int i = 0; i < n; ++i)
{
if (i == x) continue;
if (mindis1[i] + mindis2[i] > ans) ans = mindis1[i] + mindis2[i];
}
printf("%d\n", ans);
return 0;
}
相邻矩阵, o(n^2);
还可以用堆优化查找。优化到大概o(nlngn);
但是我还不太会。