表示对这类题目没feel,抽象。。。参考别人的代码后写出来的,顺便练习了一下FIFO队列实现Bellman-ford算法。。。
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <cmath> 5 using namespace std; 6 7 int g[6][105]; 8 int n,k; 9 int t[6]; 10 int d[105]; 11 int v[105]; 12 13 void init() 14 { 15 for(int i = 1;i <= n;i ++) 16 { 17 scanf("%d",&t[i]); 18 } 19 20 memset(g,0,sizeof(g)); 21 char ch; 22 int a; 23 for(int i = 1;i <= n;i ++) 24 { 25 scanf("%d",&a); 26 g[i][a] = 1; 27 int b; 28 while((ch = getchar()) != '\n') 29 { 30 scanf("%d",&b); 31 g[i][b] = 1; 32 } 33 } 34 } 35 36 void solve() 37 { 38 memset(v,0,sizeof(v)); 39 memset(d,-1,sizeof(d)); 40 d[0] = 0; 41 queue<int> q; 42 q.push(0); 43 v[0] = 1; 44 while(!q.empty()) 45 { 46 int x = q.front(); 47 q.pop(); 48 v[x] = 0; 49 for(int i = 1;i <= n;i ++) 50 { 51 if(g[i][x]) 52 { 53 for(int j = 1;j <= 100;j ++) 54 { 55 if(g[i][j]) 56 { 57 int temp = d[x] + t[i] * abs(j - x) + 60; 58 if(d[j] == -1 || temp < d[j]) 59 { 60 d[j] = temp; 61 if(!v[j]) 62 { 63 v[j] = true; 64 q.push(j); 65 } 66 } 67 } 68 } 69 } 70 } 71 } 72 73 if(d[k] == -1) 74 { 75 printf("IMPOSSIBLE\n"); 76 } 77 else if(k == 0) 78 { 79 printf("0\n"); 80 } 81 else 82 { 83 printf("%d\n",d[k]-60); 84 } 85 } 86 87 int main() 88 { 89 while(scanf("%d%d",&n,&k) == 2) 90 { 91 init(); 92 solve(); 93 } 94 95 return 0; 96 }