要你将x变换成y,一共有3×10中变换方法,每种变换有其对应的花费,然后求x-->y的最小花费,当最小花费不唯一时,求最小变换次数的解。
类似于双调路径的题,用spfa进行状态转移就行了。不过类似于 ×1, +0这种变换是没有意义的,当中间状态t > y的时候,也是不可能是最优解的,都不用加入队列中了。
#include<algorithm> #include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<queue> #define REP(i, n) for(int i=0; i<n; i++) #define FF(i, a, b) for(int i=a; i<b; i++) #define CLR(a, b) memset(a, b, sizeof(a)) using namespace std; const int maxn = 1e5 + 10; const int INF = 1e9; int x, y, c[3][11], cost[maxn], cnt[maxn]; bool inq[maxn]; queue<int> q; void relax(int u, int w1, int w2) { if(cost[u] > w1) { cost[u] = w1; cnt[u] = w2; if(!inq[u]) q.push(u); } else if(cost[u] == w1 && cnt[u] > w2) { cnt[u] = w2; if(!inq[u]) q.push(u); } } void spfa(int s) { REP(i, maxn) cost[i] = cnt[i] = INF, inq[i] = 0; cost[s] = cnt[s] = 0; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; REP(i, 10) { int v = u*10 + i; if(v > y) continue; relax(v, cost[u] + c[0][i], cnt[u] + 1); } FF(i, 1, 10) { int v = u + i; if(v > y) continue; relax(v, cost[u] + c[1][i], cnt[u] + 1); } REP(i, 10) { int v = u*i; if(v > y || i == 1) continue; relax(v, cost[u] + c[2][i], cnt[u] + 1); } } } int main() { int kase = 1; while(~scanf("%d%d", &x, &y)) { REP(i, 3) REP(j, 10) scanf("%d", &c[i][j]); spfa(x); printf("Case %d: %d %d\n", kase++, cost[y], cnt[y]); } return 0; }