UVA 12664 Interesting Calculator(spfa)

要你将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;
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值