您的位置:首页 > 其它

CodeForces - 376C Divisible by Seven(数论:同余定理)(找规律)

2017-03-12 21:38 399 查看
Divisible by Seven

You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation
so that the resulting number will be divisible by 7.

Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number
also mustn't contain any leading zeroes.

Input

The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains
digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains
at least 4 and at most 106 characters.

Output

Print a number in the decimal notation without leading zeroes — the result of the permutation.

If it is impossible to rearrange the digits of the number a in the required manner, print 0.

Examples

input
1689


output
1869


input
18906


output
18690


ps:
比如说有一个数为1234561689,那么根据同余定理可以知道1234561689%7=(1234560000%7+1689%7)%7
然后呢,我们可以假设1689(无顺序)为后四位,那么前面所有的数%7的结果只有0~6这七种情况
所以我们可以对这七种情况打表,找出%7为0的后四位“1689”(有0的话可以让0放在最后面,其他非1689的数原样输出就好了)

代码:
#include<stdio.h>
#include<string.h>
#define maxn 1000000+10
char a[][5]={"1869","6198","1896","1689","1986","1968","1698"};
char s[maxn];
int flag[11]={0};

int main()
{
scanf("%s",s);
int len=strlen(s);
int p=0,ps=0;
for(int i=0;i<len;i++)
{
if((s[i]=='1'||s[i]=='6'||s[i]=='8'||s[i]=='9')&&!flag[s[i]-'0'])
flag[s[i]-'0']=1;
else if(s[i]=='0')
ps++;
else
{
printf("%c",s[i]);
p=p*10+s[i]-'0';
p%=7;
}
}
printf("%s",a[p]);
for(int i=0;i<ps;i++)
printf("0");
return 0;
}


打表代码:
#include<stdio.h>
int a[5]={1,6,8,9},vis[20];

void dfs(int k,int s,int cnt)
{
if(cnt==4)
{
if((((s%7)+(k*10000%7))%7)==0)
printf("k=%d s=%d\n",k,s);
}
for(int i=0;i<4;i++)
{
if(!vis[a[i]])
{
vis[a[i]]=1;
dfs(k,s*10+a[i],cnt+1);
vis[a[i]]=0;
}
}
}

int main()
{
int i1,i2,i3,i4;
for(int i=0;i<7;i++)
{
dfs(i,0,0);
}
}


总结:现在接触的数论题大多都是找规律,而且大多可以通过打表找到
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: