Codeforces 601A The Two Routes【最短路】

本文介绍了一种在特定约束条件下规划火车与汽车路径的方法,确保两者不会在同一站点(除起点和终点外)同时到达,避免碰撞风险。通过构建图结构并运用Floyd算法求解最短路径问题,实现安全高效的路线规划。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A. The Two Routes
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 ≤ 4000 ≤ 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 ≤ nu ≠ 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 test(s)
input
4 2
1 3
3 4
output
2
input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
output
-1
input
5 5
4 2
3 5
4 5
5 1
1 2
output
3
Note

In the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.

In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.



题意:给定n个站点,任意两个站点之间都是相连的。每经过一条边,花费时间1。现在给出m条火车线,剩下的全是公路。汽车只能走公路,火车只能走火车线。现在火车和汽车同时从站点1出发,目的地是站点n,要求在火车和汽车行驶过程中,除了站点1和n可以同时到达,其它站点都不能同时到达。问是否存在一条方案使得火车和汽车都能到达站点n,若存在输出火车和汽车到达站点n所需的时间,反之输出-1。



思路:设Map[i][j] = 1表示i和j之间是否有火车线相连,反之是公路。则对于Map[1][n],可以分类讨论。

一、Map[i][j] = 1,火车可以从站点1直接到达站点n,我们只需要考虑汽车。

二、Map[i][j] = 0,汽车可以从站点1直接到达站点n,我们只需要考虑火车。

建好图,最后求一次最短路就可以了。


AC代码:


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#define INF 0x3f3f3f
#define eps 1e-8
#define MAXN (400+10)
#define MAXM (100000)
#define Ri(a) scanf("%d", &a)
#define Rl(a) scanf("%lld", &a)
#define Rf(a) scanf("%lf", &a)
#define Rs(a) scanf("%s", a)
#define Pi(a) printf("%d\n", (a))
#define Pf(a) printf("%.2lf\n", (a))
#define Pl(a) printf("%lld\n", (a))
#define Ps(a) printf("%s\n", (a))
#define W(a) while(a--)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define MOD 1000000007
#define LL long long
#define lson o<<1, l, mid
#define rson o<<1|1, mid+1, r
#define ll o<<1
#define rr o<<1|1
using namespace std;
bool Map[MAXN][MAXN];
int d[MAXN][MAXN];
void Floyd(int n)
{
    for(int k = 1; k <= n; k++)
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                d[i][j] = min(d[i][j], d[i][k]+d[k][j]);
}
int main()
{
    int n, m; Ri(n); Ri(m);
    for(int i = 0; i < m; i++)
    {
        int a, b; Ri(a); Ri(b);
        Map[a][b] = Map[b][a] = true;
    }
    if(Map[1][n])
    {
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                if(Map[i][j])
                    d[i][j] = INF;
                else
                    d[i][j] = 1;
            }
        }
    }
    else
    {
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                if(!Map[i][j])
                    d[i][j] = INF;
                else
                    d[i][j] = 1;
            }
        }
    }
    Floyd(n);
    printf(d[1][n] == INF ? "-1\n" : "%d\n", d[1][n]);
    return 0;
}



### Codeforces 平台上的短路径算法题目 #### Dijkstra 算法的应用实例 当面对构建短路径树的需求时,可以采用Dijkstra算法来解决。该方法的核心在于优先选择当前节点能够延伸出去的多条候选边中具有小权重的一条作为扩展方向;而在仅存在唯一一条可能的拓展边的情况下,则直接选取这条边继续探索过程[^1]。 ```python import heapq def dijkstra(graph, start): n = len(graph) dist = [float('inf')] * n dist[start] = 0 heap = [(0, start)] while heap: current_dist, u = heapq.heappop(heap) if current_dist != dist[u]: continue for v, weight in graph[u].items(): alt = dist[u] + weight if alt < dist[v]: dist[v] = alt heapq.heappush(heap, (alt, v)) return dist ``` #### Floyd-Warshall 算法处理复杂情况下的优化策略 对于涉及多个源点之间的短路径计算问题,Floyd-Warshall是一个有效的解决方案。然而,在某些特定场景下(比如本题),通过预先给定的信息可以直接定位受影响的部分并加以简化,从而避免不必要的全量遍历操作,达到降低时间复杂度的效果。值得注意的是,在累加过程中应当选用`long long`类型的变量以防止溢出错误的发生[^2]。 #### 单源短路径查询案例解析 考虑到从指定起点出发前往其余各个顶点间的短距离需求,此情形适用于单源短路径类别的算法实现方式。具体而言,即是从某固定位置开始测量至其它任意可达地点的距离长度,并针对不可达的情形输出特殊标记值 `-1` 表明无法访问的状态[^3]。 ```cpp #include<bits/stdc++.h> using namespace std; const int INF=0x3f3f3f; vector<pair<int,int>> adj[100]; int dis[100]; void spfa(int src){ queue<int> q; vector<bool> vis(100,false); fill(dis,dis+100,INF); dis[src]=0;q.push(src); while(!q.empty()){ int cur=q.front();q.pop(); vis[cur]=false; for(auto& edge : adj[cur]){ int next=edge.first,cost=edge.second; if(dis[next]>dis[cur]+cost){ dis[next]=dis[cur]+cost; if(!vis[next]){ vis[next]=true; q.push(next); } } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值