Make it Divisible by 25

Codeforce 1593.Make it Divisible by 25

题目


由于本人英语太差再加上cf题找规律偏多,我习惯性直接看样例

分析易知,本题是要处理一串数字使它变成25的倍数。

题解

25的倍数的末两位只会是00、25、50、75四种情况之一,所以只需要从后往前扫地删除多余数字即可。模拟时用数组存储四种情况即可,不用一开始就来大模拟(然而霖笨比不仅开了四个栈模拟还语法出错了orz)。
第一次写完运行后发现所有ans都比正确答案多了1,一气之下输出ans-1,没想到还成功ac了。当然好学的孩子会再找找到底是哪里问题,发现记录位数写的是n=x.size()。事实上string字符串是从下标0开始存储,所以应该是n=x.size()-1。

#include<bits/stdc++.h>
using namespace std;
const string sub[]={"00","25","50","75"};
const int inf=INT_MAX;

int solve(string& x,string& y){
    int n=x.size()-1;
    int cnt=0;
    while(n>=0&&x[n]!=y[1]){
        n--;cnt++;
    }
    if(n<0) return inf;
    n--;
    while(n>=0&&x[n]!=y[0]){
        n--;cnt++;
    }
    return n<0?inf:cnt;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int t;cin>>t;
    while(t--){
        string a;
        cin>>a;
        int ans=INT_MAX;
        for(auto i:sub){
            ans=min(ans,solve(a,i));
        }
        cout<<ans<<endl;
    }
    return 0;
}

题外话

不得不感慨为什么同样的思路却有千奇百怪的写法。归根到底,还是题刷少了,实现思路的编程能力太差,还是以写出优雅简洁的代码为目标奋斗吧。

posted @ 2021-11-02 16:10  Chilyyy  阅读(155)  评论(0)    收藏  举报