SUG 502: Digits Permutation

Time Limit: 2000MS Memory Limit: 262144KB 64bit IO Format: %I64d & %I64u

[]   [Go Back]   [Status]  

Description

Andrew has just made a breakthrough in the world of number 17: he realized that it's rather easy to permute the digits in almost any given number to get a number divisible by 17. You are given a positive integer n. You must find a permutation of its digits that is divisible by 17.

Input

Input file contains single integer n, 1 ≤ n ≤ 10 17.

Output

Output any permutation of digits of n that is divisible by 17. The output permutation may not start with a zero. If there is no such permutation, output -1.

Sample Input

sample input
sample output
17
17

sample input
sample output
2242223
2222342

sample input
sample output
239
-1

//DFS过程中将存在前导0的字典序做特判(优化),直接暴力DFS就过了!
#include<stdio.h>
#include<string.h> 
#include<algorithm>
using namespace std;
#define maxn 20
#define LL __int64

char s[maxn],str[maxn];
bool used[maxn];
int len,sign;
LL get_num(char *ss)
{
	LL t=0;
	int i;
	for(i=0;i<strlen(ss);i++)
		t=t*10+ss[i]-'0';
	return t;
}

void dfs(int p) 
{	
	if(p==len)
	{
		if(str[0]=='0')
			return;
		LL n=get_num(str);
		if(n%17==0)
		{
			printf("%I64d\n",n);
			sign=1;
			return;
		}
	}
	if(sign)
		return;
	if(str[0]=='0') //题目要求不允许存在前导0
		return; 
	int i;
	for(i=0;i<len;i++)
	{	
		if(!used[i])
		{
			used[i]=true;
			
			str[p]=s[i];
			dfs(p+1);
			used[i]=false;
			while(i+1<len&&s[i+1]==s[i]) i++;
		}
	}
}

int main()
{
	while(~scanf("%s",&s))
	{
		len=strlen(s);
		LL n=get_num(s);
		if(n%17==0)
		{
			printf("%I64d\n",n);
			continue;
		}
		sort(s,s+strlen(s));
		memset(used,false,sizeof(used));
		str[len]='\0';
		sign=0;
		dfs(0);
		if(!sign)
			puts("-1");
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值