ZOJ 1298题解,想到算法就不难了,要求多米诺骨牌最后落下的位置。这是Dijkstra算法的简单应用。设立的几个关键点,都是从1开始倒比如只有两个点1 2,最后牌倒得位置是2

 1 #include<stdio.h>
2 #include <string.h>
3
4 int main()
5 {
6 int t=0, a, b, l, n, m, i, j, k, now, maxs, x, y;
7 int cost[501][501], dist[501], s[501];
8 float time, temp;
9
10 while(scanf("%d%d", &n, &m), n)
11 {
12 for(a=1; a<=n; a++)
13 for(b=1; b<=n; b++)
14 cost[a][b] = 0;
15 for(i=1; i<=n; i++)
16 dist[i] = 200000000;
17
18 for(i=0; i<m; i++)
19 {
20 scanf("%d%d%d", &a, &b, &l);
21 cost[a][b] = cost[b][a] = l;
22 }
23
24 t++;
25 printf("System #%d\n", t);
26
27 memset(s, 0, sizeof(s));
28 now = 1;
29 dist[1] = 0;
30 s[1] = 1;
31 for(i=1; i<=n; i++)
32 {
33 maxs = 200000000;
34 for(j=1; j<=n; j++)
35 if(cost[now][j] && dist[j] > dist[now] + cost[now][j])
36 dist[j] = dist[now] + cost[now][j];
37 for(j=1; j<=n; j++)
38 if( !s[j] && maxs > dist[j])
39 {
40 maxs = dist[j];
41 now = j;
42 }
43 s[now] = 1;
44 }
45 maxs = 0;
46 x = 1;
47 for(i=1; i<=n; i++)
48 if(dist[i] > maxs)
49 maxs = dist[i];
50 time = 0;
51 k = 1;
52 for(i=1; i<=n; i++)
53 if(maxs == dist[i])
54 for(j=1; j<=n; j++)
55 if(cost[i][j])
56 {
57 temp = (cost[i][j] + dist[j] - dist[i]) * 1.0 / 2 + dist[i];
58 if(temp > time)
59 {
60 time = temp;
61 if(time == dist[i])
62 {
63 k = 1;
64 x = i;
65 }
66 if(time > dist[i])
67 {
68 k = 0;
69 x = i;
70 y = j;
71 }
72 }
73 }
74 if( k )
75 printf("The last domino falls after %.1f seconds, at key domino %d.\n", time, x);
76 else
77 printf("The last domino falls after %.1f seconds, between key dominoes %d and %d.\n", time, x>y?y:x, x>y?x:y);
78 printf("\n");
79 }
80 return 0;
81 }
posted @ 2011-10-16 18:12  zhongya  阅读(259)  评论(0编辑  收藏  举报