一个完全图
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; }
原文地址:https://www.cnblogs.com/WTSRUVF/p/9603774.html
时间: 2024-10-11 17:45:29