暴力回溯,用位运算加个奇偶剪枝
注意取余的效率,因为取余实在太慢了,所以要最少的进行取余运算,所以就是每19位进行次取余,这样1s内就过了
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <stdio.h> int ans[50]; char nok(int now) { int i,t; unsigned long long r; for(i=r=t=0;i<now;i++,t++) { r=r*10+ans[i]; if(t==18)//19位 { t=0; r%=now; } } return r%now; } int n,m; char dfs(int now) { if(now>m)return 1; int i=(now==1),f=now&1,t=now-1; for(;i<10;i++) { ans[t]=i; if(now>=n&&((!f&&(i&1))||nok(now)))continue;//奇偶 if(dfs(now+1))return 1; } return 0; } int main() { int T,C=0; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); printf("Case %d: ",++C); if(!dfs(1))printf("-1\n"); else { int i; for(i=0;i<m;i++) printf("%d",ans[i]); puts(""); } } }
时间: 2024-12-21 08:19:12