分治算法
阿新 • • 發佈:2017-12-07
stat scan ima ++ ide gif open 本質 can
算法思路:
實例: 乒乓球賽程安排:
實現:
(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 10View Code//這裏假設是從編號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 }
分治算法