acm每日一练之擅长排列的小明
2013-10-21 15:04
302 查看
描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
输入第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
样例输出
code;
code2:
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
输入第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
2 3 1 4 2
样例输出
1 2 3 12 13 14 21 23 24 31 32 34 41 42 43
code;
import java.io.PrintWriter; import java.util.Scanner; public class Test { static Scanner scin = new Scanner(System.in); static PrintWriter scout = new PrintWriter(System.out); static int n, m; static int rcd[] = new int[10];// 用于输出 static int num[] = new int[10]; // 存放输入数 static int used[] = new int[10];// 判断是否已经使用 public static void main(String[] args) { int t, i; for (i = 0; i < 10; i++) num[i] = i + 1; t = scin.nextInt(); while (t-- > 0) { n = scin.nextInt(); m = scin.nextInt(); for (i = 0; i < 10; i++) used[i] = 1; unrepeat_permutation(0); } scout.close(); } static void unrepeat_permutation(int l) { int i; if (l == m) { for (i = 0; i < m; i++) scout.print(rcd[i]); scout.println(); scout.flush(); return; } for (i = 0; i < n; i++) // 从1开始枚举n个数 { if (used[i] > 0) { used[i]--; // 使用次数减1 rcd[l] = num[i]; // 把num[i]的值放在l的位置 unrepeat_permutation(l + 1); // 填下一个数 used[i]++; // 恢复使用--以某一前缀开头的递归运行完后要做到不影响其它前缀的递归,所以要恢复; } } } }
code2:
import java.util.Scanner; public class Main{ public static int n, r; public static StringBuffer string; public static boolean mark[]; public static void dfs(int k) { if (k < r) { for (int i = 1; i <= n; i++) { if (!mark[i]) { string.append(i); mark[i] = true; dfs(k + 1); mark[i] = false; string.deleteCharAt(k); } } } else { System.out.println(string); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int cases = scanner.nextInt(); while (cases-- != 0) { n = scanner.nextInt(); r = scanner.nextInt(); mark = new boolean[n + 1]; string = new StringBuffer(); dfs(0); } } }
相关文章推荐
- ACM 擅长排列的小明
- ACM 19 擅长排列的小明 java
- ACM 擅长排列的小明
- 练习场acm 题目19 擅长排列的小明
- (STL) ACM_擅长排列的小明.(补)
- 擅长排列的小明
- NYOJ 469 擅长排列的小明 II
- nyoj19 擅长排列的小明
- nyoj--19--擅长排列的小明(dfs)
- (NYoj 469)擅长排列的小明 II --简单地推规律,打表思想
- 擅长排列的小明 II
- NYOJ19,擅长排列的小明,StringBuffer.deleteCharAt()
- 擅长排列的小明和D的小L
- nyoj19 擅长排列的小明 (排列组合)
- NYOJ_469_擅长排列的小明 II
- nyoj469 擅长排列的小明 II
- NYOJ 19 擅长排列的小明
- NYOJ 469 擅长排列的小明 II
- 擅长排列的小明
- 擅长排列的小明