【kuangbin带你飞】专题四 最短路练习
比赛链接
【kuangbin带你飞】专题四 最短路练习
A - Til the Cows Come Home
题目描述
Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.
Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.
Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.
Input
-
Line 1: Two integers: T and N
-
Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.
Output
- Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.
Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90
Hint
INPUT DETAILS:
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.
解题思路
最短路模板题~
dijkstra
- 时间复杂度:\(O(mlogn)\)
spfa
- 时间复杂度:\(O(kn)\)
代码
//dijkstra求最短路
#include<queue>
#include<cstdio>
#include<cstring>
#define mp make_pair
#define pb push_back
using namespace std;
typedef pair<int,int> pii;
int n,m,d[1010];
bool v[1010];
vector<pii> adj[1010];
void dijkstra()
{
priority_queue<pii,vector<pii>,greater<pii>> q;
q.push(mp(0,1));
memset(d,0x3f,sizeof d);
d[1]=0;
while(q.size())
{
int x=q.top().second;
q.pop();
if(v[x])continue;
v[x]=true;
for(int i=0;i<adj[x].size();i++)
{
int y=adj[x][i].first,w=adj[x][i].second;
if(d[y]>d[x]+w)
{
d[y]=d[x]+w;
q.push(mp(d[y],y));
}
}
}
}
int main()
{
scanf("%d%d",&m,&n);
while(m--)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
adj[x].pb(mp(y,w));
adj[y].pb(mp(x,w));
}
dijkstra();
printf("%d",d[n]);
return 0;
}
//spfa求最短路
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int N=1010;
int n,m,d[N];
vector<pair<int,int>> adj[N];
bool v[N];
void spfa()
{
queue<int> q;
q.push(1);
v[1]=true;
memset(d,0x3f,sizeof d);
d[1]=0;
while(q.size())
{
int x=q.front();
q.pop();
v[x]=false;
for(int i=0;i<adj[x].size();i++)
{
int y=adj[x][i].first,w=adj[x][i].second;
if(d[y]>d[x]+w)
{
d[y]=d[x]+w;
q.push(y);
v[y]=true;
}
}
}
}
int main()
{
scanf("%d%d",&m,&n);
while(m--)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
adj[x].push_back(make_pair(y,w));
adj[y].push_back(make_pair(x,w));
}
spfa();
printf("%d",d[n]);
return 0;
}
B - Frogger
题目描述
Freddy Frog is sitting on a stone in the middle of a lake. Suddenly he notices Fiona Frog who is sitting on another stone. He plans to visit her, but since the water is dirty and full of tourists' sunscreen, he wants to avoid swimming and instead reach her by jumping.
Unfortunately Fiona's stone is out of his jump range. Therefore Freddy considers to use other stones as intermediate stops and reach her by a sequence of several small jumps.
To execute a given sequence of jumps, a frog's jump range obviously must be at least as long as the longest jump occuring in the sequence.
The frog distance (humans also call it minimax distance) between two stones therefore is defined as the minimum necessary jump range over all possible paths between the two stones.
You are given the coordinates of Freddy's stone, Fiona's stone and all other stones in the lake. Your job is to compute the frog distance between Freddy's and Fiona's stone.
Input
The input will contain one or more test cases. The first line of each test case will contain the number of stones n (2<=n<=200). The next n lines each contain two integers xi,yi (0 <= xi,yi <= 1000) representing the coordinates of stone #i. Stone #1 is Freddy's stone, stone #2 is Fiona's stone, the other n-2 stones are unoccupied. There's a blank line following each test case. Input is terminated by a value of zero (0) for n.
Output
For each test case, print a line saying "Scenario #x" and a line saying "Frog Distance = y" where x is replaced by the test case number (they are numbered from 1) and y is replaced by the appropriate real number, printed to three decimals. Put a blank line after each test case, even after the last one.
Sample Input
2
0 0
3 4
3
17 4
19 4
18 5
0
Sample Output
Scenario #1
Frog Distance = 5.000
Scenario #2
Frog Distance = 1.414
解题思路
floyd
floyd
跟dp
思路一样,可以用来求最短路,本题并不是求最短路,而是求所有路径上最大边的最小值,不妨将floyd
的状态表示改变一下,即:表示所有路径上最大边的最小值,则有状态转移方程:
\(f[i][j]\) 原意是表示 \(i\) 到 \(j\) 的距离,\(max(f[i][k],f[k][j])\) 表示经过 \(k\) ,\(i\) 到 \(j\) 的最大边
- 时间复杂度:\(O(n^3)\)
dijkstra
同理,有dijkstra和spfa解法
- 时间复杂度:\(O(mlogn)\)
spfa
- 时间复杂度:\(O(kn)\)
代码
//floyd变形
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=210;
//f[i][j]表示从i到j的所有路径上最长边的最小值
double f[N][N];
int x[N],y[N],n;
double dis(int i,int j)
{
return sqrt(1.*(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
void floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
f[i][j]=min(f[i][j],max(f[i][k],f[k][j]));
}
int main()
{
int t=0;
while(scanf("%d",&n),n)
{
for(int i=1;i<=n;i++)scanf("%d%d",&x[i],&y[i]);
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
f[i][j]=f[j][i]=dis(i,j);
floyd();
printf("Scenario #%d\n",++t);
printf("Frog Distance = %.3lf\n\n",f[1][2]);
}
return 0;
}
//dijkstra变形
#include<cmath>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
typedef pair<int,int> pii;
typedef pair<double,int> pdi;
const int N=210;
vector<pdi> adj[N];
pii a[N];
int n;
double d[N];
bool v[N];
double dis(pii a,pii b)
{
return sqrt(1.*(a.first-b.first)*(a.first-b.first)+(a.second-b.second)*(a.second-b.second));
}
void dijkstra()
{
memset(v,0,sizeof v);
for(int i=2;i<=n;i++)d[i]=1e9;
d[1]=0;
priority_queue<pdi,vector<pdi>,greater<pdi>> q;
q.push(make_pair(0,1));
while(q.size())
{
int x=q.top().second;
q.pop();
if(v[x])continue;
v[x]=true;
for(int i=0;i<adj[x].size();i++)
{
int y=adj[x][i].second;
double w=adj[x][i].first;
if(d[y]>max(d[x],w))
{
d[y]=max(d[x],w);
q.push(make_pair(d[y],y));
}
}
}
}
int main()
{
int t=0;
while(scanf("%d",&n),n)
{
for(int i=1;i<=n;i++)scanf("%d%d",&a[i].first,&a[i].second);
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
{
double w=dis(a[i],a[j]);
adj[i].push_back(make_pair(w,j));
adj[j].push_back(make_pair(w,i));
}
dijkstra();
printf("Scenario #%d\n",++t);
printf("Frog Distance = %.3lf\n\n",d[2]);
for(int i=1;i<=n;i++)adj[i].clear();
}
return 0;
}
//spfa变形
#include<cmath>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
typedef pair<int,int> pii;
typedef pair<double,int> pdi;
const int N=210;
vector<pdi> adj[N];
pii a[N];
int n;
double d[N];
bool v[N];
double dis(pii a,pii b)
{
return sqrt(1.*(a.first-b.first)*(a.first-b.first)+(a.second-b.second)*(a.second-b.second));
}
void spfa()
{
for(int i=2;i<=n;i++)d[i]=1e9;
memset(v,0,sizeof v);
queue<int> q;
q.push(1);
v[1]=true;
d[1]=0;
while(q.size())
{
int x=q.front();
q.pop();
v[x]=false;
for(int i=0;i<adj[x].size();i++)
{
int y=adj[x][i].second;
double w=adj[x][i].first;
if(d[y]>max(d[x],w))
{
d[y]=max(d[x],w);
q.push(y);
v[y]=true;
}
}
}
}
int main()
{
int t=0;
while(scanf("%d",&n),n)
{
for(int i=1;i<=n;i++)scanf("%d%d",&a[i].first,&a[i].second);
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
{
double w=dis(a[i],a[j]);
adj[i].push_back(make_pair(w,j));
adj[j].push_back(make_pair(w,i));
}
spfa();
printf("Scenario #%d\n",++t);
printf("Frog Distance = %.3lf\n\n",d[2]);
for(int i=1;i<=n;i++)adj[i].clear();
}
return 0;
}
C - Heavy Transportation
题目描述
Background
Hugo Heavy is happy. After the breakdown of the Cargolifter project he can now expand business. But he needs a clever man who tells him whether there really is a way from the place his customer has build his giant steel crane to the place where it is needed on which all streets can carry the weight.
Fortunately he already has a plan of the city with all streets and bridges and all the allowed weights.Unfortunately he has no idea how to find the the maximum weight capacity in order to tell his customer how heavy the crane may become. But you surely know.
Problem
You are given the plan of the city, described by the streets (with weight limits) between the crossings, which are numbered from 1 to n. Your task is to find the maximum weight that can be transported from crossing 1 (Hugo's place) to crossing n (the customer's place). You may assume that there is at least one path. All streets can be travelled in both directions.
Input
The first line contains the number of scenarios (city plans). For each city the number n of street crossings (1 <= n <= 1000) and number m of streets are given on the first line. The following m lines contain triples of integers specifying start and end crossing of the street and the maximum allowed weight, which is positive and not larger than 1000000. There will be at most one street between each pair of crossings.
Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. Then print a single line containing the maximum allowed weight that Hugo can transport to the customer. Terminate the output for the scenario with a blank line.
Sample Input
1
3 3
1 2 3
1 3 4
2 3 5
Sample Output
Scenario #1:
4
解题思路
本题要求我们求解所有路径最大边的最小值,跟上一题一样,改变一下即可,注意此时dijkstra
应该是大根堆,本题floyd
会超时~
代码
//floyd变形超时
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1010;
int n,m,f[N][N];
void floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
f[i][j]=max(f[i][j],min(f[i][k],f[k][i]));
}
int main()
{
int T;
scanf("%d",&T);
for(int t=1;t<=T;t++)
{
scanf("%d%d",&n,&m);
memset(f,0,sizeof f);
while(m--)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
f[x][y]=f[y][x]=w;
}
floyd();
printf("Scenario #%d:\n",t);
printf("%d\n",f[1][n]);
}
return 0;
}
//dijkstra变形
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=1010;
int d[N],n,m;
bool v[N];
vector<pair<int,int>> adj[N];
void dijkstra()
{
memset(d,0,sizeof d);
memset(v,0,sizeof v);
priority_queue<pair<int,int>> q;
q.push(make_pair(0x3f3f3f3f,1));
d[1]=0x3f3f3f3f;
while(q.size())
{
int x=q.top().second;
q.pop();
if(v[x])continue;
v[x]=true;
for(int i=0;i<adj[x].size();i++)
{
int y=adj[x][i].first,w=adj[x][i].second;
if(d[y]<min(d[x],w))
{
d[y]=min(d[x],w);
q.push(make_pair(d[y],y));
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
for(int t=1;t<=T;t++)
{
scanf("%d%d",&n,&m);
while(m--)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
adj[x].push_back(make_pair(y,w));
adj[y].push_back(make_pair(x,w));
}
dijkstra();
printf("Scenario #%d:\n",t);
printf("%d\n\n",d[n]);
for(int i=1;i<=n;i++)adj[i].clear();
}
return 0;
}
//spfa变形
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=1010;
int d[N],n,m;
bool v[N];
vector<pair<int,int>> adj[N];
void spfa()
{
memset(v,0,sizeof v);
memset(d,0,sizeof d);
queue<int> q;
q.push(1);
d[1]=0x3f3f3f3f;
v[1]=true;
while(q.size())
{
int x=q.front();
q.pop();
v[x]=false;
for(int i=0;i<adj[x].size();i++)
{
int y=adj[x][i].first,w=adj[x][i].second;
if(d[y]<min(d[x],w))
{
d[y]=min(d[x],w);
q.push(y);
v[y]=true;
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
for(int t=1;t<=T;t++)
{
scanf("%d%d",&n,&m);
while(m--)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
adj[x].push_back(make_pair(y,w));
adj[y].push_back(make_pair(x,w));
}
spfa();
printf("Scenario #%d:\n",t);
printf("%d\n\n",d[n]);
for(int i=1;i<=n;i++)adj[i].clear();
}
return 0;
}
D - Silver Cow Party
题目描述
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
Hint
Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.
解题思路
要求单源最短路与到单源最短路(即折返最短路),关键在于求折返最短路,我们不妨使用邻接矩阵,原始矩阵求的是单源最短路,即从 \(X\) 到其他各点之间的最短距离,而我们要求的折返最短路则是从其他各点到 \(X\) 之间的最短距离,我们可以把邻接矩阵反过来,再按照单源最短路的算法求解
\(\color{red}{这样为什么是对的?}\)
不妨考虑两个点之间的双向最短路,起点到终点即单源最短路,将终点到起点的路径反过来,求解的就是起点到终点的最短路,假设存在一条折返最短路,如果求解最短路时还有比该最短路还短的路径,说明将路径反过来后,折返最短路还要更短,与原假设矛盾,证毕
这里以spfa
为例
- 时间复杂度:\(O(kn)\)
代码
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=3010;
int n,m,a[N][N],X;
int d[N],d_inv[N];
bool v[N];
void spfa(int X)
{
memset(d,0x3f,sizeof d);
memset(v,0,sizeof v);
queue<int> q;
q.push(X);
v[X]=true;
d[X]=0;
while(q.size())
{
int x=q.front();
q.pop();
v[x]=false;
for(int y=1;y<=n;y++)
{
if(d[y]>d[x]+a[x][y])
{
d[y]=d[x]+a[x][y];
if(!v[y])
q.push(y),v[y]=true;
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&X);
memset(a,0x3f,sizeof a);
for(int i=1;i<=n;i++)a[i][i]=0;
while(m--)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
a[x][y]=min(a[x][y],w);
}
spfa(X);
for(int i=1;i<=n;i++)d_inv[i]=d[i];
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
swap(a[i][j],a[j][i]);
spfa(X);
int res=0;
for(int i=1;i<=n;i++)res=max(res,d[i]+d_inv[i]);
printf("%d",res);
return 0;
}