POJ-3579 二分答案
Posted dlamdlam
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ-3579 二分答案相关的知识,希望对你有一定的参考价值。
题目链接: http://poj.org/problem?id=3579
题意: 通俗易懂
思路: 二分答案即可
总结: 基本的二分操作
代码如下:
1 import java.util.*; 2 3 public class Main { 4 public static int[] a; 5 6 public static int n; 7 public static int k; 8 public static long an; 9 10 public static void main(String[] args) { 11 Scanner sc = new Scanner(System.in); 12 while (sc.hasNext()) { 13 n = sc.nextInt(); 14 an = ((long) n * (n - 1)) >> 1; 15 an = (an + 1) >> 1; 16 a = new int[n]; 17 for (int i = 0; i < n; ++i) { 18 a[i] = sc.nextInt(); 19 } 20 Arrays.sort(a); 21 int left = -1; 22 int right = a[n - 1] - a[0] + 1; 23 while (right - left > 1) { 24 int mid = (left + right) >> 1; 25 if (C(mid)) { 26 right = mid; 27 } else 28 left = mid; 29 } 30 System.out.println(right); 31 } 32 } 33 34 public static boolean C(int mid) { 35 int j = 0; 36 int count = 0; 37 for (int i = 1; i < n; i++) { 38 while (a[i] - a[j] > mid) 39 j++; 40 count += (i - j); 41 } 42 return count >= an; 43 } 44 }
以上是关于POJ-3579 二分答案的主要内容,如果未能解决你的问题,请参考以下文章