P1875 佳佳的魔法药水
题目链接:
官方题解: 做法:我们可以用Dijkstra的思想,用已知来更新未知。 我们用一个v数组来标记一种药水的最小花费是否确定,如果v[i]为真,则表示i号药水的最小花费已经确定,否则反之。 同时,用cost[i]和ans[i]记录当前求出的i号药水的最小花费和满足最小花费的方案个数, f[i][j]记录一个i号药水和一个j号药水能够合成的药水编号(是不是很像邻接矩阵?), cost[i]初始化为药水在商店中的价格,ans[i]初始化为1。 每次选择一个v[k]为假并且cost[k]最小的k, 可以证明这个k号药水再没有其他方案使得它的最小花费更小了,然后寻找与它相关联的配方,如果k号药水可以跟另一个最小花费已经确定的j号药水合成一种药水, 则更新cost[f[j][k]]和ans[f[j][k]]:如果cost[j]+cost[k]<cost[f[j][k]], 则将cost[f[j][k]]更新为cost[j]+cost[k],并将ans[i]更新为1; 如果cost[j]+cost[k]=cost[f[j][k]],则将ans[f[j][k]]加上ans[j]*ans[k]。 更新完所有和k号药水有关的配方之后,将v[k]赋值为真, 重复上述过程直到所有药水都更新过为止。 最后输出cost[0]和ans[0]即可。
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int N = 1010; int n; bool st[N]; int cnt[N]; int dist[N]; int map[N][N]; void dijkstra() { for (int i = 0; i < n; i ++ ) { int t = -1; for (int j = 0; j < n; j ++ ) if (!st[j] && (t == -1 || dist[t] > dist[j])) t = j; if (st[t]) continue; st[t] = true; for (int j = 0; j < n; j ++ ) if (st[j] && map[t][j] != 0x3f3f3f3f) { if (dist[map[t][j]] > dist[t] + dist[j]) { dist[map[t][j]] = dist[t] + dist[j]; cnt[map[t][j]] = cnt[t] * cnt[j]; } else if (dist[map[t][j]] == dist[t] + dist[j]) cnt[map[t][j]] += cnt[t] * cnt[j]; } } } int main() { cin >> n; memset(map, 0x3f, sizeof map); memset(dist, 0x3f, sizeof dist); for (int i = 0; i < n; i ++ ) cnt[i] = 1; for (int i = 0; i < n; i ++ ) cin >> dist[i]; int a, b, c; while (scanf("%d %d %d", &a, &b, &c) != EOF) map[a][b] = map[b][a] = min(c, map[a][b]); dijkstra(); cout << dist[0] << " " << cnt[0] << endl; return 0; }