E. Divisibility by 25
time limit per test1 second
memory limit per test256 megabytes
You are given an integer n from 1 to 1018 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.
Input
The first line contains an integer n (1≤n≤1018). It is guaranteed that the first (left) digit of the number n is not a zero.
Output
If it is impossible to obtain a number that is divisible by 25, print -1. Otherwise print the minimum number of moves required to obtain such number.
Note that you can swap only adjacent digits in the given number.
Examples
inputCopy
5071
outputCopy
4
inputCopy
705
outputCopy
1
inputCopy
1241367
outputCopy
-1
Note
In the first example one of the possible sequences of moves is 5071 → 5701 → 7501 → 7510 → 7150.
题意: 给你一个数,每次操作可以任意移动相邻的两位数,求得使用最少的操作使得最后的数可以被25整除,如果怎么移动都不行,输出-1,否则输出最少的操作数
分析: 很显然,只要最后两位数是以 " 00 " , " 25 " , " 50 " , " 75 " "00", "25", "50", "75" "00","25","50","75"结尾的数都可以被25整除,所以我们只需暴力的枚举这四种类型即可,然后取个最小值,在枚举每一位时,我们要贪心的来取,先使得最近的数放在最后一个位置,然后在保证倒数第二个数位正确的数,然后我们还要注意,保证第一个数不为零,在移动完这两个数,我们还要记录下第一个不为零的数的位置,代码写的很丑,…
参考代码
#include<bits/stdc++.h>
using namespace std;
int a[11];
string s;
int f(string x) {
if (x[0] == '0' && a[0] < 2) {
return -1;
}
if (x[0] != '0') {
if (!a[x[0] - '0'] || !a[x[1] - '0']) return -1;
}
string t = s;
int r = t.size() - 1;
while (t[r] != x[1]) {
r--;
}
int cnt = t.size() - r - 1;
for (int i = r; i < t.size() - 1; i++) swap(t[i], t[i + 1]);
r = t.size() - 2;
while (t[r] != x[0]) {
r--;
}
cnt += t.size() - r - 2;
for (int i = r; i < t.size() - 2; i++) swap(t[i], t[i + 1]);
int cc = 0;
while (t[cc] == '0') cc++;
if (cc + 2 > s.size()) return -1;
if (cc) return cc + cnt;
return cnt;
}
int main() {
cin >>s;
for (auto it : s) {
a[it - '0']++;
}
if ((a[0] > 1) || (a[2] && a[5]) || (a[0] && a[5]) || (a[7] && a[5])) {
int res = 1e9;
string s[4] = {"25", "50", "75", "00"};
for (int i = 0; i < 4; i++) {
int t = f(s[i]);
if (t != -1) {
res = min(res, t);
}
}
cout << res << endl;
} else puts("-1");
return 0;
}