L i n k Link Link
l u o g u P 1629 luogu\ P1629 luogu P1629
D e s c r i p t i o n Description Description
有一个邮递员要送东西,邮局在节点 1 1 1。他总共要送 n − 1 n-1 n−1 样东西,其目的地分别是节点 2 2 2 到节点 n n n。由于这个城市的交通比较繁忙,因此所有的道路都是单行的,共有 m m m 条道路。这个邮递员每次只能带一样东西,并且运送每件物品过后必须返回邮局。求送完这 n − 1 n-1 n−1 样东西并且最终回到邮局最少需要的时间。
I n p u t Input Input
第一行包括两个整数, n n n 和 m m m,表示城市的节点数量和道路数量。
第二行到第 ( m + 1 ) (m+1) (m+1) 行,每行三个整数, u , v , w u,v,w u,v,w,表示从 u u u 到 v v v 有一条通过时间为 w w w 的道路。
O u t p u t Output Output
输出仅一行,包含一个整数,为最少需要的时间。
S a m p l e Sample Sample I n p u t Input Input
5 10
2 3 5
1 5 5
3 5 6
1 2 8
1 3 8
5 3 4
4 1 8
4 5 3
3 5 6
5 4 2
S a m p l e Sample Sample O u t p u t Output Output
83
H i n t Hint Hint
对于
30
30%
30 的数据,
1
≤
n
≤
200
1 \leq n \leq 200
1≤n≤200。
对于
100
100%
100 的数据,
1
≤
n
≤
1
0
3
1 \leq n \leq 10^3
1≤n≤103,
1
≤
m
≤
1
0
5
1 \leq m \leq 10^5
1≤m≤105
,
1
≤
u
,
v
≤
n
1\leq u,v \leq n
1≤u,v≤n,
1
≤
w
≤
1
0
4
1 \leq w \leq 10^4
1≤w≤104 ,输入保证任意两点都能互相到达。
T r a i n Train Train o f of of T h o u g h t Thought Thought
第一想法是每个点一次
S
P
F
A
SPFA
SPFA,然后发现会炸
隔壁巨佬一句正反来一遍以
1
1
1号点
S
P
F
A
SPFA
SPFA就好了啊点醒蒟蒻
求其余点到1号点的最短路,其实就等于将路径反过来,再从终点(1号点)出发跑一遍最短路
因此这道题就转化为一道求两次最短路的题目
C o d e Code Code
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
int n, ans, t, tt, m;
int c[1005], h[1005], hh[1005], dis[1005], disx[1005];
struct Node
{
int next, to, w;
}node[200005];
struct Nodex
{
int next, to, w;
}nodex[200005];
void SPFA()//正向SPFA
{
for (int i = 1; i <= n; i++)
dis[i] = 1e9;
memset(c, 0, sizeof(c));
c[1] = 1;
queue<int>Q;
Q.push(1);
dis[1] = 0;
while(Q.size())
{
int xt = Q.front();
Q.pop();
for (int i = h[xt]; i; i = node[i].next)
{
int tt = node[i].to;
if (dis[xt] + node[i].w < dis[tt])
{
dis[tt] = dis[xt] + node[i].w;
if (!c[tt])
{
c[tt] = 1;
Q.push(tt);
}
}
}
c[xt] = 0;
}
}
void spfa()//反向SPFA
{
for (int i = 1; i <= n; i++)
disx[i] = 1e9;
memset(c, 0, sizeof(c));
c[1] = 1;
queue<int>Q;
Q.push(1);
disx[1] = 0;
while(Q.size())
{
int xt = Q.front();
Q.pop();
for (int i = hh[xt]; i; i = nodex[i].next)
{
int tt = nodex[i].to;
if (disx[xt] + nodex[i].w < disx[tt])
{
disx[tt] = disx[xt] + nodex[i].w;
if (!c[tt])
{
c[tt] = 1;
Q.push(tt);
}
}
}
c[xt] = 0;
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
node[++t] = (Node){h[u], v, w}; h[u] = t;//记录原图
nodex[++tt] = (Nodex){hh[v], u, w}; hh[v] = tt;//记录反向图
}
SPFA();
spfa();
for (int i = 1; i <= n; ++i)
{
if (dis[i] != 1e9 && disx[i] != 1e9 && i != 1)
ans += dis[i] + disx[i];
}
printf("%d", ans);
return 0;
}