最短路(Dijkstra) POJ 1062 昂贵的聘礼
1 /*
2 最短路:Dijkstra算法,首先依照等级差距枚举“删除”某些点,即used,然后分别从该点出发生成最短路
3 更新每个点的最短路的最小值
4 注意:国王的等级不一定是最高的:)
5 */
6 #include <cstdio>
7 #include <iostream>
8 #include <algorithm>
9 #include <cmath>
10 #include <map>
11 #include <vector>
12 #include <cstring>
13 #include <string>
14 using namespace std;
15
16 const int MAXN = 1e2 + 10;
17 const int INF = 0x3f3f3f3f;
18
19 int d[MAXN];
20 int cost[MAXN][MAXN];
21 int x[MAXN];
22 int lv[MAXN];
23 int used[MAXN];
24
25 int Dijkstra(int n)
26 {
27 for (int i=1; i<=n; ++i) d[i] = cost[0][i];
28
29 for (int i=1; i<=n; ++i)
30 {
31 int x = 0;
32 int mn = INF;
33 for (int j=1; j<=n; ++j)
34 {
35 if (!used[j] && d[j] < mn) mn = d[x=j];
36 }
37 if (x == 0) break;
38 used[x] = 1;
39 for (int j=1; j<=n; ++j)
40 {
41 if (!used[j] && cost[x][j] > 0)
42 d[j] = min (d[j], d[x] + cost[x][j]);
43 }
44 }
45
46 return d[1];
47 }
48
49 int main(void) //POJ 1062 昂贵的聘礼
50 {
51 //freopen ("C.in", "r", stdin);
52
53 int n, m;
54
55 while (~scanf ("%d%d", &m, &n))
56 {
57 memset (used, 0, sizeof (used));
58 memset (d, 0, sizeof (d));
59 memset (cost, 0, sizeof (cost));
60 for (int i=1; i<=n; ++i)
61 {
62 scanf ("%d%d%d", &cost[0][i], &lv[i], &x[i]);
63 for (int j=1; j<=x[i]; ++j)
64 {
65 int t, u;
66 scanf ("%d%d", &t, &u);
67 cost[t][i] = u;
68 }
69 }
70
71 int tmp, ans = INF, maxlv;
72 for (int i=1; i<=n; ++i)
73 {
74 maxlv = lv[i];
75 for (int j=1; j<=n; ++j)
76 {
77 if (lv[j] > maxlv || maxlv - lv[j] > m) used[j] = 1;
78 else used[j] = 0;
79 }
80 tmp = Dijkstra (n);
81 ans = min (ans, tmp);
82 }
83
84 printf ("%d\n", ans);
85 }
86
87 return 0;
88 }
编译人生,运行世界!