日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

POJ 2456 - Aggressive cows(二分)

發布時間:2023/11/29 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 POJ 2456 - Aggressive cows(二分) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Description

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,…,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don’t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

Input

  • Line 1: Two space-separated integers: N and C

  • Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output

  • Line 1: One integer: the largest minimum distance

Sample Input

5 3
1
2
8
4
9

Sample Output

3

Hint

OUTPUT DETAILS:

FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.

Huge input data,scanf is recommended.


題目大意:農夫養牛,牛喜歡打架,所以兩個牛的距離越遠越好。輸入n m,n個房間,m頭牛。依次輸入房間坐標。如何分配房間使得每個牛直接的距離都盡量大,求滿足這個條件兩個牛房間距離的最小值

Solution:先對輸入的房間坐標進行排序,然后二分查找即可。第一個房間先放一只牛,a[f]為上一頭牛所在房間坐標 如果mid為所求解 當且僅當a[i]-a[f]≥mid。如果滿足條件sum+1。如果sum大于等于m,說明mid小于所求解,更新l=mid。


#include <stdio.h> #include <string.h> #include <math.h> #include<algorithm> #include <iostream> using namespace std; const int N = 100010; int a[N]; int n, m;int judge(int mid) {int f = 0;//f為 上一頭牛 所在的房間號int sum = 1;//記錄房間總數for (int i = 1; i < n; i++){if (a[i] - a[f] >= mid)//如果mid為所求解 當且僅當a[i]-a[f]大于等于mid{f=i;sum++;}else continue;}if (sum >= m) return 1;else return 0;}int main() {scanf("%d%d", &n, &m);for (int i = 0; i < n; i++)scanf("%d", &a[i]);sort(a, a + n);int l = -1;int r = 1000000000;int ans;while (r - l >= 0){int mid = (l + r) / 2;if (judge(mid) == 1){ans = mid;l = mid;}else r = mid;if (r - l == 1) //終止條件break;}printf("%d\n", ans);return 0; }

轉載于:https://www.cnblogs.com/Chizhao/p/10439770.html

總結

以上是生活随笔為你收集整理的POJ 2456 - Aggressive cows(二分)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。