标签:
#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+邻接矩阵)
标签:
原文地址:http://www.cnblogs.com/atmacmer/p/5216549.html