zoukankan      html  css  js  c++  java
  • Codeforces Round #486 (Div. 3) E. Divisibility by 25

    Codeforces Round #486 (Div. 3) E. Divisibility by 25

    题目连接:

    http://codeforces.com/group/T0ITBvoeEx/contest/988/problem/E

    Description

    You are given an integer n from 1 to 10^18 without leading zeroes.

    In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.

    What is the minimum number of moves you have to make to obtain a number that is divisible by 25? Print -1 if it is impossible to obtain a number that is divisible by 25.

    Sample Input

    5071
    
    

    Sample Output

    4
    

    题意

    给定一个数,只能交换相邻元素,最少交换几次使得数能被25整除?

    题解:

    只有末尾是 00, 25, 50, 75才能被整除。将对应数字先移到末尾,再移动倒数第二个数字,是最短的步骤,比较四个情况最少步骤即可。

    代码

    #include <bits/stdc++.h>
    
    using namespace std;
    
    string d;
    int ans;
    
    int getnumber(int a,int b) {
        int top = d.size();
        int cnt=0;
        string s = d;
        if (b!=s[top-1]) {
            int i=top-2;
            for (i=top-2;i>=0;i--) if (s[i]==b) break;
            if (i>=0) {
                cnt = top-1-i;
                for (;i<top-1;i++) swap(s[i],s[i+1]);
            } else return 0x7fffffff;
        }
        if (a!=s[top-2]) {
            int i=top-3;
            for (i=top-3;i>=0;i--) if (s[i]==a) break;
            if (i>=0) {
                cnt += top-2-i;
                for (;i<top-2;i++) swap(s[i],s[i+1]);
            } else return 0x7fffffff;
        }
        if (s[0]=='0') {
            int i=0;
            for (;i<top;i++) if (s[i]!='0') break;
            if (i<top-2) {
                cnt += i;
                for (;i;i--) swap(s[i],s[i-1]);
            } else return 0x7fffffff;
        }
        if (s[top-2]==a && s[top-1]==b) return cnt;
        else return 0x7fffffff;
    }
    
    int main() {
        cin>>d;
        ans = 0x7fffffff;
        ans = min(ans,getnumber('0','0'));
        ans = min(ans,getnumber('2','5'));
        ans = min(ans,getnumber('5','0'));
        ans = min(ans,getnumber('7','5'));
        cout << (ans == 0x7fffffff?-1:ans);
    }
    
  • 相关阅读:
    IDEA在编辑时提示could not autowire
    python基础——使用__slots__
    python基础——实例属性和类属性
    python基础——继承和多态
    python基础——访问限制
    python基础——面向对象编程
    python基础——第三方模块
    python基础——使用模块
    python基础——模块
    Python tkinter调整元件在窗口中的位置与几何布局管理
  • 原文地址:https://www.cnblogs.com/EDGsheryl/p/9153686.html
Copyright © 2011-2022 走看看