标签:
Description
Input
Output
Sample Input
3 2 1 2 2 3 2 3 1 2 1 2
Sample Output
0
题解:简单的最短路。
迪杰斯特拉:
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int INF= 0x3fffffff; int map[120][120]; bool visited[120]; int d[120]; void prim(int n,int s) { memset(visited,false,sizeof(visited)); for(int i = 1;i <= n;i++) { d[i] = map[s][i]; } visited[s] = true; for(int i = 1;i < n;i++) { int min = INF; int k; for(int j = 1;j <= n;j++) { if(!visited[j] && min > d[j]) { min = d[j]; k = j; } } if(min == INF) { break; } visited[k] = true; for(int j = 1;j <= n;j++) { if(!visited[j] && d[j] > d[k] + map[k][j]) { d[j] = d[k] + map[k][j]; } } } } int main() { int N,A,B; while(scanf("%d%d%d",&N,&A,&B) != EOF) { int n,num; for(int i = 1;i <= N;i++) { for(int j = 1;j <= N;j++) { if(i == j) { map[i][j] = 0; } else { map[i][j] = INF; } } } for(int i = 1;i <= N;i++) { scanf("%d",&n); for(int j = 0;j < n;j++) { scanf("%d",&num); if(j == 0) { map[i][num] = 0; } else { map[i][num] = 1; } } } prim(N,A); if(d[B] != INF) { printf("%d\n",d[B]); } else { printf("-1\n"); } } return 0; }
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int INF= 0x3fffffff; int map[120][120]; bool visited[120]; int d[120]; void spfa(int n,int s) { memset(visited,false,sizeof(visited)); for(int i = 1;i <= n;i++) { d[i] = INF; } queue<int> q; d[s] = 0; q.push(s); visited[s] = true; while(!q.empty()) { int x = q.front(); q.pop(); visited[x] = false; for(int i = 1;i <= n;i++) { if(d[i] > d[x] + map[x][i]) { d[i] = d[x] + map[x][i]; if(!visited[i]) { q.push(i); visited[i] = true; } } } } } int main() { int N,A,B; while(scanf("%d%d%d",&N,&A,&B) != EOF) { int n,num; for(int i = 1;i <= N;i++) { for(int j = 1;j <= N;j++) { if(i == j) { map[i][j] = 0; } else { map[i][j] = INF; } } } for(int i = 1;i <= N;i++) { scanf("%d",&n); for(int j = 0;j < n;j++) { scanf("%d",&num); if(j == 0) { map[i][num] = 0; } else { map[i][num] = 1; } } } spfa(N,A); if(d[B] != INF) { printf("%d\n",d[B]); } else { printf("-1\n"); } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wang2534499/article/details/47751515