P1824 進擊的奶牛 AC於2018.11.4
阿新 • • 發佈:2018-12-19
題目描述
Farmer John建造了一個有N(2<=N<=100,000)個隔間的牛棚,這些隔間分佈在一條直線上,座標是x1,...,xN (0<=xi<=1,000,000,000)。
他的C(2<=C<=N)頭牛不滿於隔間的位置分佈,它們為牛棚裡其他的牛的存在而憤怒。為了防止牛之間的互相打鬥,Farmer John想把這些牛安置在指定的隔間,所有牛中相鄰兩頭的最近距離越大越好。那麼,這個最大的最近距離是多少呢?
輸入輸出格式
輸入格式:
第1行:兩個用空格隔開的數字N和C。
第2~N+1行:每行一個整數,表示每個隔間的座標。
輸出格式:
輸出只有一行,即相鄰兩頭牛最大的最近距離。
輸入輸出樣例
輸入樣例#1:
5 3 1 2 8 4 9
輸出樣例#1:
3
#include<cstdio> #include<iostream> #include<algorithm> #include<cstdlib> #include<cstring> #include<numeric> #include<ctype.h> using namespace std; int a[100001]; int n,m,a1; bool check(int x) { int num=0; int l=a[1]; for(int i=2;i<=n;i++) { if(a[i]-l<x) num++; else l=a[i]; if(num>a1) return false; } return true; } int main() { int l=1,r; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+1+n); a1=n-m; r=a[n]-a[1]; while(l+1<r) { int mid=(l+r)/2; if(check(mid)) l=mid; else r=mid; } if(check(r)) printf("%d",r); else printf("%d",l); return 0; }