分治算法

算法思路:

 

实例: 乒乓球赛程安排:

 

实现:

(1) 分解: 首先把8人赛程安排划分为4人:

(2) 求解: 然后再把4人赛程划分为2人:

(3) 合并: 合并成4人赛程

 

 

 1 import java.util.Scanner;
 2 
 3 public class FenZhi {
 4 
 5     private static Scanner in;
 6 
 7     public static int[][] fenzhi(int[][] a, int k, int n) {
 8 
 9         
10         //这里假设是从编号1开始处理的
11         if (n == 2) {
12             a[k][1] = k;
13             a[k][2] = k + 1;
14             a[k + 1][1] = k + 1;
15             a[k + 1][2] = k;
16 
17             return a;
18         }
19 
20         //分治算法,本质上是两次递归
21         a = fenzhi(a, k, n / 2);
22         a = fenzhi(a, k + n / 2, n / 2);
23 
24         // 填充右上角
25         for (int i = k; i < k + n / 2; i++) {
26             for (int j = 1 + n / 2; j <= n; j++) {
27                 a[i][j] = a[i + n / 2][j - n / 2];
28             }
29         }
30 
31         // 填充右下角
32         for (int i = k + n / 2; i <= n; i++) {
33             for (int j = 1 + n / 2; j <= n; j++) {
34                 a[i][j] = a[i - n / 2][j - n / 2];
35             }
36         }
37 
38         return a;
39     }
40 
41     public static void main(String[] args) {
42 
43         in = new Scanner(System.in);
44         System.out.print("请输入你想开始的编号: ");
45         int k = in.nextInt();
46         System.out.print("请输入您想要处理的数量: ");
47         int n = in.nextInt();
48 
49         int[][] a = new int[n + 1][n + 1];
50         a = fenzhi(a, k, n);
51 
52         for (int i = 1; i <= n; i++) {
53             for (int j = 1; j <= n; j++) {
54                 System.out.print(a[i][j] + "\t");
55             }
56             System.out.println();
57         }
58     }
59 
60 }
View Code

 

posted @ 2017-12-07 16:05  fengze  阅读(201)  评论(0编辑  收藏  举报