题意:有m位n进制整数非常神奇:乘以2,3...,m之后,所有得到的数恰好是原数各数字的一个排列,输入m,n,求出这样的整数(最多只有一个)
思路:枚举0~n-1的数,因为乘以m次后得到不同的排列,所以我们可以根据这个求出m个数来,然后再用排列树搜索答案,最后check一下
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,a[10],p[10],b[10],cnt[405],vis[405];
int fk(){
int c[10];
for (int i = 0; i < m; i++)
b[i] = c[i] = a[p[i]];
c[m] = 0;
for (int k = 2; k <= m; k++){
for (int i = 0; i < m; i++){
c[i+1] += (c[i]+b[i])/n;
c[i] = (c[i]+b[i]) % n;
}
if (c[m])
return 0;
int flag = 1;
for (int i = 0; i < m; i++)
vis[c[i]]++;
for (int i = 0; i < m; i++)
if (vis[c[i]] != cnt[c[i]])
flag = 0;
for (int i = 0; i < m; i++)
vis[c[i]] = 0;
if (!flag)
return 0;
}
return 1;
}
int dfs(int u){ //排列树
if (u == m)
return fk();
for (int i = u; i <= m-1; i++){
swap(p[i],p[u]);
if (dfs(u+1))
return 1;
swap(p[i],p[u]);
}
return 0;
}
int check(int x){
if (!x)
return 0;
int t = 0;
for (int i = 0; i < m; i++){
t = (t + x) % n;
a[i] = t;
p[i] = i;
}
memset(cnt,0,sizeof(cnt));
memset(vis,0,sizeof(vis));
for (int i = 0; i < m; i++)
cnt[a[i]]++;
return dfs(0);
}
int main(){
while (scanf("%d%d",&m,&n) != EOF && n+m){
int flag = 0;
for (int i = 0; i < n; i++)
if (check(i)){
flag = 1;
break;
}
if (!flag)
printf("Not found.\n");
else {
printf("%d",b[m-1]);
for (int i = m-2; i >= 0; i--)
printf(" %d",b[i]);
printf("\n");
}
}
return 0;
}