码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-06-08 10:38:15      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:include   ==   pos   ORC   rom   clu   space   cout   contest   

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

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

标签:include   ==   pos   ORC   rom   clu   space   cout   contest   

原文地址:https://www.cnblogs.com/EDGsheryl/p/9153686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!