SPFA裸题,练手练手~
#include <cstdio> #include <algorithm> #include <cstring> #include <queue> using namespace std; int const maxn = 2*10005; struct node{ int u,v,w,next; node(){} node(int _u,int _v,int _w,int _next){ u = _u; v = _v; w = _w; next = _next; } }Edge[maxn]; int n,p; int head[maxn],Count; int toque[maxn],dis[maxn]; bool inque[maxn]; void AddEdge(int u,int v,int w){ Count++; Edge[Count] = node(u,v,w,head[u]); head[u] = Count; } bool spfa(){ dis[1]=0; queue<int>Q; Q.push(1); inque[1]=true; while( !Q.empty() ){ int now = Q.front(); Q.pop(); inque[now]=false; toque[now]++; if(toque[now]>=n) return false; for(int i=head[now];i;i=Edge[i].next){ int w = Edge[i].w; int v = Edge[i].v; if(dis[now]+w<dis[v]){ dis[v] = dis[now]+w; if(!inque[v]){ Q.push(v); inque[v] = true; } } } } return false; } int main(){ memset(dis,0x3f3f3f3f,sizeof(dis)); scanf("%d%d",&n,&p); for(int i=1;i<=p;i++){ int x,y; scanf("%d%d",&x,&y); AddEdge(x,y,1); AddEdge(y,x,1); } spfa(); int Max = -1; for(int i=1;i<=n;i++) Max = max(Max,dis[i]); printf("%d\n",Max); return 0; }