cf486(div.3)E Divisibility by 25 贪心

题目大意


给定一个不大于10^18的不含前导零的正整数n,求最小的k使得交换相邻两位k次后得到的新数字是25的倍数
要求每次交换都不能出现前导零

Solution


终于想起了我cf可怜的rating,似乎打完educationround之后就一直在掉掉掉
火速码完前几题就开始死刚这个了,打得我意识模糊,果然还是太菜了。。

利用小学生数学姿势可以发现25的倍数末尾一定是00、25、50、75,因此只需要对这些数字移动即可。需要注意这样贪心过程中可能出现前导零,需要找到第一位非0换到前面去
昨晚大概是困懵了敲着2k+的模拟和各种奇怪判断乱搞都过不了第八个点,今早起来改改就A了也真是蓝瘦

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define copy(x,t) memcpy(x,t,sizeof(x))

typedef long long LL;
const int INF=0x3f3f3f3f;

char str[21],tmp[21];
int bct[21],n,ans=INF;

int solve(char a,char b) {
    copy(str,tmp);
    int ret=0,pos;
    for (pos=n;pos;pos--) if (str[pos]==b) break;
    if (!pos) return INF;
    for (;pos<n;pos++,ret++) std:: swap(str[pos],str[pos+1]);
    for (pos=n-1;pos;pos--) if (str[pos]==a) break;
    if (!pos) return INF;
    for (;pos<n-1;pos++,ret++) std:: swap(str[pos],str[pos+1]);
    for (pos=1;pos<=n;pos++) if (str[pos]!='0') break;
    for (;pos>1;pos--,ret++) std:: swap(str[pos],str[pos-1]);
    if (str[n-1]!=a||str[n]!=b) ret=INF;
    return ret;
}

int main(void) {
    scanf("%s",str+1); n=strlen(str+1);
    copy(tmp,str);
    ans=std:: min(ans,solve('0','0'));
    ans=std:: min(ans,solve('2','5'));
    ans=std:: min(ans,solve('5','0'));
    ans=std:: min(ans,solve('7','5'));
    if (ans==INF) ans=-1;
    printf("%d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jpwang8/article/details/80551223