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

时间:2024-09-05 22:35:50

一个完全图

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

另一个跑遍最短路即可

#include <bits/stdc++.h>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
const int maxn = , INF = 0x7fffffff;
int head[maxn], cnt, n, m;
int vis[maxn], d[maxn];
bool w[][];
struct node
{
int u, v, next;
}Node[maxn<<]; 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=; i<=n; i++) d[i] = INF;
mem(vis, );
Q.push(s);
vis[s] = ;
d[s] = ;
while(!Q.empty())
{
int u = Q.front(); Q.pop();
vis[u] = ;
for(int i=head[u]; i!=-; i=Node[i].next)
{
node e = Node[i];
if(d[e.v] > d[u] + )
{
d[e.v] = d[u] + ;
if(!vis[e.v])
{
vis[e.v] = ;
Q.push(e.v);
}
}
}
}
} int main()
{
mem(head, -);
cnt = ;
cin>> n >> m;
int u, v, flag = ;
for(int i=; i<m; i++)
{
scanf("%d%d", &u, &v);
if(u == && v == n || u == n && v == )
flag = ;
w[u][v] = w[v][u] = ;
add(u, v);
}
if(flag)
{
mem(head, -);
cnt = ;
for(int i=; i<=n; i++)
{
for(int j=i+; j<=n; j++)
{
if(!w[i][j])
add(i, j);
}
}
} // cout<< "111" <<endl;
spfa();
if(d[n] == INF)
{
cout<< "-1" <<endl;
return ;
}
cout<< d[n] <<endl; return ;
}