题目链接:点击打开链接
题意:
给定m( 3<=m<=6), n ( 4<=n<=400)
构造一个m位n进制的数。
使得这个数*2, *3, *i ( 2<=i<=m)的结果是 这个数的排列组合。
如:
m = 6, n = 10;
则 这个数可能为 142857
2*142857 = 285714
3*142857 = 428571
4*142857 = 571428
5*142857 = 714285
6*142857 = 857142
输出:
题目保证至多只有一个解,若有这样的解则输出这个数(每位数间有一个空格)若无输出"Not found."
思路:
枚举个位,然后不断用 (2~m)去乘个位得到其他位,则这样得到的结果的某种排列才有可能是答案,
判断所有排列是否可行。
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Scanner; import java.util.TreeSet; import java.util.Queue; public class Main { int m, n; boolean ok; int[] ans = new int[7], b = new int[500], a = new int[500]; boolean check(int x, int[] y){ for(int i = 0; i < n; i++)a[i] = b[i]; int tmp = 0; for(int i = m; i >= 1; i--){ tmp = tmp + x*y[i]; int k = tmp %n; if(--a[k] < 0)return false; tmp /= n; } return tmp == 0; } boolean[] use = new boolean[7]; int[] v = new int[7]; boolean dfs(int pos){ if(pos > m){ for(int i = 2; i <= m; i++) if(false == check(i,v))return false; for(int i = 1; i <= m; i++)ans[i] = v[i]; return true; } else { for(int i = 1; i <= m; i++){ if(use[i])continue; use[i] = true; v[pos] = ans[i]; if(true == dfs(pos+1))return true; use[i] = false; } return false; } } boolean judge(int x){ int tmp = 0; for(int i = 0; i < n; i++)b[i] = 0; for(int i = 1; i <= m; i++){ tmp = (x + tmp)%n; ans[i] = tmp; b[ans[i]]++; use[i] = false; } return dfs(1); } void put(int x[]){ out.print(x[1]); for(int i = 2; i <= m; i++)out.print(" "+x[i]); out.println(); } void work() { while(true){ m = cin.nextInt(); n = cin.nextInt(); if(m == 0 && n == 0)break; ok = false; for (int i = 1; i < n && ok == false; i++) if (judge(i)) ok = true; if(ok) put(ans); else out.println("Not found."); } } Main() { cin = new Scanner(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { Main e = new Main(); e.work(); out.close(); } public Scanner cin; public static PrintWriter out; }
时间: 2024-10-12 00:32:33