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);
    }
    
  • 相关阅读:
    AVLTree的实现以及左右旋转维持自平衡
    哈希函数之布隆过滤器
    LeetCode——线段树解决区间总和问题
    第23章 Windows身份验证
    第22章 使用外部身份提供商登录
    第21章 登录
    第20章 定义客户端
    第19章 定义资源
    第18章 启动
    第17章 社区快速入门和模板
  • 原文地址:https://www.cnblogs.com/EDGsheryl/p/9153686.html
Copyright © 2011-2022 走看看