Codeforces Round #333 (Div. 2) C. The Two Routes flyod
C. The Two Routes
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://codeforces.com/contest/602/problem/C
Description
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.
A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.
You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.
Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.
Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v).
You may assume that there is at most one railway connecting any two towns.
Output
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1.
Sample Input
4 2
1 3
3 4
Sample Output
2
HINT
题意
给你一个完全图,里面的边不是火车道就是汽车道,然后任意时刻,火车和汽车都不能相遇在除了1,n的其他点
每条边的边权值都是1,然后问你最小时间使得两种车都能到达n点
题解:
因为是完全图,那么总有一种车可以只花费1就能从起点走到终点
然后剩下那个车跑一发最短路就好了~
代码:
#include<iostream> #include<stdio.h> #include<queue> using namespace std; int mp1[450][450]; int mp2[450][450]; const int inf = 1e7+7; int main() { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i==j)mp1[i][j]=mp2[i][j]=0; else mp1[i][j]=mp2[i][j]=inf; for(int i=1;i<=m;i++) { int x,y;scanf("%d%d",&x,&y); mp1[x][y]=mp1[y][x]=1; } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i!=j) { if(mp1[i][j]==1)mp2[i][j]=inf; else mp2[i][j]=1; } int flag = mp1[1][n]; if(flag == inf) { for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) mp1[i][j]=min(mp1[i][j],mp1[i][k]+mp1[k][j]); if(mp1[1][n]==inf)return puts("-1"); else printf("%d\n",mp1[1][n]); } else { for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) mp2[i][j]=min(mp2[i][j],mp2[i][k]+mp2[k][j]); if(mp2[1][n]==inf)return puts("-1"); else printf("%d\n",mp2[1][n]); } }