CodeForces ~ 988E ~ Divisibility by 25 (模拟)

本文介绍了一种算法,该算法通过模拟交换数字字符串中相邻数字的位置来寻找将任意长整数变成25的倍数所需的最少步骤。文章详细解释了如何针对不同的目标结尾(如00、25、50、75)进行最优操作,并给出了具体的实现代码。

题意:给你一个数字n(n1e18)n(n≤1e18),你每次可以交换他的相邻的两位上的数字,使得这个整数变为整除25的数字的最小步数为多少?如果不能输出-1。

思路:整除25,那么末尾两位为:00,25,50,75时均可以,模拟每种情况,求一个最小值就好。

#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000007;
int ans;
string str;
void solve(char a, char b)
{
    string s = str;
    int cnt1 = s.rfind(a), cnt2 = s.rfind(b);
    if (a == '0' && b == '0') cnt1 = s.rfind(a, cnt1-1);
    if (cnt1 == string::npos || cnt2 == string::npos)
        return ;
    int cnt = 0;
    //对于ab的情况,我们先把b移动到最后一位,然后把a移动到倒数第二位
    //如果b在a前面,我们先把b看作a,a看作b,移动到最后两位后,交换ba即可
    if (cnt1 > cnt2) cnt++, swap(cnt1, cnt2);
    for (int i = cnt2; i+1 < s.size(); i++) cnt++, swap(s[i], s[i+1]);
    for (int i = cnt1; i+1 < s.size()-1; i++) cnt++, swap(s[i], s[i+1]);
    //如果操作完以后第一位为'0'了,那么我们找到第一个不为0的数字,把他交换到第一位即可
    cnt += find_if(s.begin(), s.end(), [](char c){ return c != '0'; }) - s.begin();
    ans = min(ans, cnt);
}
int main()
{
    cin >> str;
    ans = INF;
    solve('0', '0');
    solve('2', '5');
    solve('5', '0');
    solve('7', '5');
    if (ans == INF) ans = -1;
    printf("%d\n", ans);
    return 0;
}
/*
507
52231
50267
*/
### Codeforces Round 988 Div. 3 的题目及题解 #### A. Add to Nearest Integer 在这个问题中,给定一个浮点数 \( x \),目标是将其四舍五入到最接近的整数。如果该数字恰好位于两个整数之间,则应向绝对值更大的方向舍入。 ```cpp #include <iostream> #include <cmath> using namespace std; void solve() { double x; cin >> x; cout << round(x) << endl; } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { solve(); } } ``` 此代码通过 `round` 函数实现了对输入浮点数的处理[^1]。 #### B. Array Sharpening 对于这个问题,有一个长度为 \( n \) 的数组 \( a \),需要找到是否存在一对索引 \( i \neq j \),使得 \( |a_i - a_j| \ge k \)[^2]。 ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; bool canBeSharped(vector<int>& nums, int diff) { sort(nums.begin(), nums.end()); for (size_t i = 0; i < nums.size() - nums[i]) >= diff) return true; } return false; } void solve() { int n, k; cin >> n >> k; vector<int> a(n); for (auto& ai : a) cin >> ai; cout << (canBeSharped(a, k) ? "YES" : "NO") << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); size_t tests; cin >> tests; while(tests --> 0) solve(); return 0; } ``` 这段程序首先对接收到的数据进行了排序,接着遍历查找是否有满足条件的一对元素。 #### C. Minimum Grid Path Cost 本题涉及在一个二维网格上的路径规划,其中每一步都有一定的花费。目的是计算从左上角移动至右下角所需的最小费用总和[^3]。 由于未提供具体算法实现细节,在这里仅描述思路而不展示完整的源码片段。通常这类问题可以通过动态规划来解决,维护一个二维表记录到达各位置时累积成本最低的情况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值