存两个图,一正一反,用SPFA求X点的单元最短路,正反两个DIST之和的最大值即为答案。
#include <stdio.h>
#include <string.h>
#define MAXN 1010
#define MAXM MAXN*MAXN
#define inf 1000000000
int head[2][MAXN], pnt[2][MAXM], length[2][MAXM], next[2][MAXM];
int tot[2];
int dist[2][MAXN];
int queue[MAXM];
int inq[MAXN];
int countq[MAXN];
int n,m,x;
int a,b,len;
void addedge(int func,int a,int b,int len)
{
pnt[func][tot[func]]=b;
length[func][tot[func]]=len;
next[func][tot[func]]=head[func][a];
head[func][a]=tot[func]++;
}
int spfa(int func)
{
int qhead=0;
int qtail=1;
for (int i=0; i<n; i++) {
inq[i]=0;
countq[i]=0;
dist[func][i]=inf;
}
dist[func][x-1]=0;
queue[qhead]=x-1;
while (qhead<qtail) {
int idx=head[func][queue[qhead]];
while (~idx) {
if(dist[func][queue[qhead]] + length[func][idx] < dist[func][pnt[func][idx]]) {
dist[func][pnt[func][idx]] = dist[func][queue[qhead]] + length[func][idx];
if(!inq[pnt[func][idx]]) {
inq[pnt[func][idx]]=1;
countq[pnt[func][idx]]++;
if(countq[pnt[func][idx]] > n+1) return 0;
queue[qtail++]=pnt[func][idx];
}
}
idx=next[func][idx];
}
inq[queue[qhead]]=0;
qhead++;
}
return 1;
}
int main()
{
scanf("%d%d%d",&n,&m,&x);
for(int i=0; i<2; i++) {
for (int j=0; j<n; j++) {
head[i][j]=-1;
}
for (int j=0; j<m; j++) {
next[i][j]=-1;
}
tot[i]=0;
}
for(int i=0; i<m; i++) {
scanf("%d%d%d",&a,&b,&len);
addedge(0,a-1,b-1,len);
addedge(1,b-1,a-1,len);
}
spfa(0);
spfa(1);
int max=-inf;
for(int i=0;i<n;i++) {
if(dist[0][i]+dist[1][i]>max) {
max=dist[0][i]+dist[1][i];
}
}
printf("%d\n",max);
}
浙公网安备 33010602011771号