The Two Routes CodeForces - 601A(水最短路)

Posted wtsruvf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了The Two Routes CodeForces - 601A(水最短路)相关的知识,希望对你有一定的参考价值。

一个完全图

1和n肯定有一条路  不是公路就是铁路  另=

另一个跑遍最短路即可

#include <bits/stdc++.h>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
const int maxn = 100100, INF = 0x7fffffff;
int head[maxn], cnt, n, m;
int vis[maxn], d[maxn];
bool w[500][500];
struct node
{
    int u, v, next;
}Node[maxn<<1];

void add_(int u, int v)
{
    Node[cnt].u = u;
    Node[cnt].v = v;
    Node[cnt].next = head[u];
    head[u] = cnt++;
} 
void add(int u, int v)
{
    add_(u, v);
    add_(v, u);
}

void spfa(int s)
{
    queue<int> Q;
    for(int i=0; i<=n; i++) d[i] = INF;
    mem(vis, 0);
    Q.push(s);
    vis[s] = 1;
    d[s] = 0;
    while(!Q.empty())
    {
        int u = Q.front(); Q.pop();
        vis[u] = 0;
        for(int i=head[u]; i!=-1; i=Node[i].next)
        {
            node e = Node[i];
            if(d[e.v] > d[u] + 1)
            {
                d[e.v] = d[u] + 1;
                if(!vis[e.v])
                {
                    vis[e.v] = 1;
                    Q.push(e.v); 
                }
            }
        }
    } 
}

int main()
{
    mem(head, -1);
    cnt = 0;
    cin>> n >> m;
    int u, v, flag = 0;
    for(int i=0; i<m; i++)
    {
        scanf("%d%d", &u, &v);
        if(u == 1 && v == n || u == n && v == 1)
            flag = 1;
        w[u][v] = w[v][u] = 1;
        add(u, v);
    }
    if(flag)
    {
        mem(head, -1);
        cnt = 0;
        for(int i=1; i<=n; i++)
        {
            for(int j=i+1; j<=n; j++)
            {
                if(!w[i][j])
                    add(i, j);
            }
        }
    }

//    cout<< "111" <<endl;
    spfa(1);
    if(d[n] == INF)
    {
        cout<< "-1" <<endl;
        return 0;
    }
    cout<< d[n] <<endl;
    
    return 0;
}

 

以上是关于The Two Routes CodeForces - 601A(水最短路)的主要内容,如果未能解决你的问题,请参考以下文章

CF 602C The Two Routes(dij+邻接矩阵)

cf601a The Two Routes

CF601A The Two Routes

CF912E Prime Gift(Meeting In The Middle+Two pointers)

Two Sets CodeForces - 468B

codeforces 620D D. Professor GukiZ and Two Arrays