标签:最短路
8 7 0 1 1 2 2 3 3 4 4 5 5 6 6 7 8 8 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 0
Yes Yes
/*dijkstra*/ #include<cstdio> #include<cstring> #include<algorithm> #define MAX 0x3f3f3f using namespace std; int map[111][111],dis[111],vis[111]; int n,m; int min(int x,int y) { if(x >= y) return y; return x; } void dijkstra(int s) { int i,j,k; memset(vis, 0, sizeof(vis)); for(i = 0; i < n; i++) dis[i] = map[s][i]; vis[s]=1; while(1) { k = -1; for( i = 0; i < n; i++) if(!vis[i]&&(k==-1||dis[i] < dis[k])) k = i; if(k == -1) break; vis[k] = 1; for(i = 0; i < n; i++) dis[i] = min(dis[i],dis[k]+map[k][i]); } } int main() { int i, j, k; while(scanf("%d%d",&n,&m)!=EOF) { for(i = 0;i < n; i++) for(j = 0;j < n; j++) { if(i == j) map[i][j] = 0; else map[i][j] = MAX; } int a,b; while(m--) { scanf("%d%d",&a,&b); if(a!=b) map[a][b] = map[b][a] = 1; } int flag = 1; for(i = 0; i < n; i++) { dijkstra(i); for( j = 0; j < n;j++) { if(dis[j]>7) { flag = 0; break; } } if(flag == 0) break; } if(flag) printf("Yes\n"); else printf("No\n"); } return 0; } /*spfa*/ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<queue> #include<algorithm> using namespace std; int dis[1111],vis[1111],head[2000],edgenum; int n,m,flag; struct node{ int start,end,len,next; }p[20000]; void add(int u,int v, int w) { node E = {u,v,w,head[u]}; p[edgenum] = E; head[u] = edgenum++; } void spfa(int s,int e) { memset(vis,0,sizeof(vis)); memset(dis,0x3f,sizeof(dis)); queue<int> q; q.push(s); dis[s] = 0; vis[s] = 1; while( !q.empty() ) { int u = q.front(); q.pop(); vis[u] = 0; for(int i=head[u]; i != -1; i=p[i].next) { int v = p[i].end; if(dis[v] > dis[u]+p[i].len) { dis[v] = dis[u]+p[i].len; if(!vis[v]) { vis[v] = 1; q.push(v); } } } } if(dis[e] > 7) { flag = 1;return; } } int main() { int i,j,k; while(scanf("%d%d",&n,&m)!=EOF) { memset(head,-1,sizeof(head)); edgenum = 0; int a,b; while(m--) { scanf("%d%d",&a,&b); add(a,b,1); add(b,a,1); } flag = 0; for(i = 0; i<n; i++) { for(j = i +1; j < n; j++) { spfa(i,j); if(flag) break; } } if(flag) printf("No\n"); else printf("Yes\n"); } return 0; } /* floyd */ #include<stdio.h> #include<string.h> #define min(a,b) a>b?b:a #define INF 0x3f3f3f3f int n,m; int dis[111][111]; void floyd() { int i,j,k; for(k = 0; k < n; k++) for(i = 0; i < n; i++) for(j = 0; j < n; j++) dis[i][j] = min( dis[i][j], dis[i][k]+dis[k][j] ); } int main() { int i,j,k,a,b; while(scanf("%d%d",&n,&m)!=EOF) { memset(dis,0x3f,sizeof(dis)); while(m--) { scanf("%d%d",&a,&b); dis[a][b] = dis[b][a] = 1; } floyd(); int flag = 0; for(i = 0; i < n;i++) for(j = 0; j < n;j++) { if( flag ) break; if(dis[i][j] > 7) { flag = 1;break; } } if(flag) printf("No\n"); else printf("Yes\n"); } return 0; }
版权声明:原创文章,若要转载,请与博主联系,谢谢
标签:最短路
原文地址:http://blog.csdn.net/liu6886/article/details/47839067