CF988E Divisibility by 25 (Think + String)

Link

Title:

gives a range from 1 to 1 0 18 10^{18}101 8 integer n, but no leading zeros. In one move, you can swap any two adjacent numbers in a given number such that the resulting number does not contain leading zeros. In other words, the numbers you have cannot contain any leading zeros after each move. What is the minimum number of moves required to get a number divisible by 25? If a number divisible by 25 cannot be obtained, print -1.

analyze:

Because the result is a multiple of 25. So the last two must be 00 , 25 , 50 , 75 00,25,50,7500,25,50,7 5 . Then there is the problem of moving the prefix 0.
We can consider these four cases separately, find two characters from the back, delete them from the string, and finally count the number of prefix 0s.
Here to find characters from the back, we use the rfind() function:write stl

string str;
int f(char a,char b){
    
    
    string s=str;
    int len=s.size();
    int p1 = s.rfind(b);
    if(p1==-1) return mod;
    s.erase(p1,1);
    int p2 = s.rfind(a);
    if(p2==-1) return mod;
    s.erase(p2,1);
    int sum=0;
    while(s[sum]=='0') sum++;
    return sum+(len-1-p1)+(len-2-p2);
}
void solve(){
    
    
    cin>>str;
    int ans=min(f('0','0'),f('2','5'));
    ans=min(ans,f('5','0'));
    ans=min(ans,f('7','5'));
    if(ans==mod) puts("-1");
    else cout<<ans<<endl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326263482&siteId=291194637