Codeforces 628C Bear and String Distance 【构造】


题目链接:点我

题意:定义dist(字母1, 字母2) = 两字母ascll之差。

给定一个串a和一个值k,找到另一个串b(长度相等)使得两串各个位置的dist()之和 == k。


思路:每次尽可能大的去补,补得范围在min(k, 当前字母可以补的最大范围)。最后判断k 是否为 0。

sort一下并没有什么用。。。


AC代码:


#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#define CLR(a, b) memset(a, (b), sizeof(a))
#define PI acos(-1.0)
using namespace std;
typedef long long LL;
typedef double DD;
const int MAXN = 1e5+10;
struct Node{
    int val, id;
};
Node num[MAXN];
bool cmp1(Node a, Node b){
    return a.val > b.val;
}
int cnt[MAXN];
int main()
{
    int n, k; cin >> n >> k;
    string str, ans; cin >> str;
    for(int i = 0; i < n; i++)
    {
        num[i].val = str[i] - 'a' + 1;
        num[i].id = i;
    }
    sort(num, num+n, cmp1);
    for(int i = 0; i < n; i++)
    {
        int Max = max(26 - num[i].val, num[i].val - 1);
        int temp = min(Max, k);
        if(num[i].val + temp <= 26)
            cnt[num[i].id] = num[i].val + temp;
        else
            cnt[num[i].id] = num[i].val - temp;
        k -= temp;
    }
    if(k) cout << -1 << endl;
    else
    {
        ans = "";
        for(int i = 0; i < n; i++)
            ans += 'a' + (cnt[i]-1);
        cout << ans << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值