Algorithm


E. Divisibility by 25
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given an integer n from 11 to 10181018 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 2525? Print -1 if it is impossible to obtain a number that is divisible by 2525.

Input

The first line contains an integer n (1n10181≤�≤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 2525, 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
input
Copy
5071
output
Copy
4
input
Copy
705
output
Copy
1
input
Copy
1241367
output
Copy
-1
Note

In the first example one of the possible sequences of moves is 5071  5701  7501  7510  7150.

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <bits/stdc++.h>

using namespace std;

int m;
long long n;
vector<int> all, tmp;

int main() {
  scanf("%lld", &n);
  while(n != 0) {
  	all.push_back(n % 10);
  	n /= 10;
  }
  reverse(all.begin(), all.end());
  m = all.size();

  int res = 1000;
  for(int i = 0; i < all.size(); ++i) {
  	for(int j = 0; j < all.size(); ++j) {
  		if(i == j)
  			continue;

  		if(all[i] == 0 && all[j] == 0) {
  			res = min(res, m - i + m - j - 3);
  		} else if(all[i] == 2 && all[j] == 5 ||
  							all[i] == 5 && all[j] == 0 ||
  							all[i] == 7 && all[j] == 5) {
  			int tmp = m - i + m - j - 2 - (i < j), idx = -1;
  			for(int k = 0; k < all.size(); ++k)
  				if(all[k] == 0) {
  					idx = k;
  					break;
  				}
  			if(idx != j && idx != -1 && ((i == 0 && idx == 1) || (i == 0 && j == 1 && idx == 2) || (j == 0 && idx == 1))) {
  				for(int k = idx + 1; k < all.size(); ++k)
  					if(all[k] != 0) {
  						idx = k;
  						break;
  					}
  				if(all[idx] == 0)
  					tmp = 1e9;
  				else
  					tmp += idx - (j == 1 ? 2 : 1);
  			}
  			res = min(res, tmp);
  		}
  	}
  }

  if(res == 1000)
  	puts("-1");
  else
  	printf("%d\n", res);

  return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
5071

Output

x
+
cmd
4
Advertisements

Demonstration


Codeforces Solution-E. Divisibility by 25-Solution in C, C++, Java, Python

Previous
Codeforces solution 1080-B-B. Margarite and the best present codeforces solution
Next
CodeChef solution DETSCORE - Determine the Score CodeChef solution C,C+