Time Limit: 2000MS | Memory Limit: 262144KB | 64bit IO Format: %I64d & %I64u |
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;
}