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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CF 602C The Two Routes(dij+邻接矩阵)相关的知识,希望对你有一定的参考价值。

( ̄▽ ̄)"

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdlib>
#include<vector>
#include<stack>
#include<map>
using namespace std;
typedef long long ll;

const int INF=10e8;
const int MAXN=410;

int k,minn;
int lc[MAXN],c1[MAXN][MAXN],c2[MAXN][MAXN];
bool vis[MAXN];

int dij(int n,int c[][MAXN])
{
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++)
        lc[i]=c[1][i];
    vis[1]=1;

    for(int j=1;j<=n;j++)
    {
        k=-1,minn=INF;
        for(int i=1;i<=n;i++)
        {
            if(!vis[i]&&minn>lc[i])
            {
                minn=lc[i];
                k=i;
            }
        }
        if(k==-1) break;
        vis[k]=1;
        for(int i=1;i<=n;i++)
            if(!vis[i]&&lc[i]>lc[k]+c[k][i])
                lc[i]=lc[k]+c[k][i];
    }
    if(lc[n]==INF)
        lc[n]=-1;
    return lc[n];
}

int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    int flag=0;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(i==j)
            {
                c1[i][j]=c1[j][i]=0;
            }
            else
            {
                c1[i][j]=c1[j][i]=INF;
                c2[i][j]=c2[j][i]=INF;
            }
        }
    }

    for(int i=1;i<=m;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        c1[u][v]=c1[v][u]=1;
        if((u==1&&v==n)||(u==n&&v==1))
            flag=1;
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(c1[i][j]==0||c1[i][j]==INF)
                c2[i][j]=c2[j][i]=1;
        }
    }
    if(m==n*(n-1)/2)
        printf("-1\n");
    else
    {
        if(flag==1)
            printf("%d\n",dij(n,c2));
        else if(flag==0)
            printf("%d\n",dij(n,c1));
    }
    return 0;
}

以上是关于CF 602C The Two Routes(dij+邻接矩阵)的主要内容,如果未能解决你的问题,请参考以下文章

CF601A The Two Routes

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

CodeForces - 601A The Two Routes

CF1005C Summarize to the Power of Two 暴力 map

CF 1005C Summarize to the Power of Two hash/STL-map

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