Sheryl's ACM

一条默默划水的咸鱼

导航

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);
}

posted on 2018-06-08 05:57  EDGsheryl  阅读(270)  评论(0编辑  收藏  举报