Advanced algorithms - half

The following is a code for the subject through the above OJ

· Example:

Subject description:

  Farmer John built a long corral, which includes N (2 ≤ N ≤ 100,000) compartments, these cubicles are numbered x1, ..., xN (0 ≤ xi ≤ 1,000,000,000). However, John the C (2 ≤ C ≤ N) cows who do not like the layout, and a few head of cattle in a compartment, they battle to happen. To keep cattle hurt each other. John decided to allocate its own compartment to cattle, the minimum distance between any two cows as large as possible, then, what is the largest minimum distance is it

Code:

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 const int N=1e5+3;
 8 int n,m,x[N];
 9 
10 inline bool check(int d)
11 {
12     int cow=1;
13     int rgt=x[1]+d;
14     for(int i=2;i<=n;++i)
15     {
16         if(x[i]<rgt) continue;
17         ++cow;
18         rgt=x[i]+d;
19     }
20     return cow>=m;
21 }
22 
23 int main()
24 {
25     scanf("%d%d",&n,&m);
26     for(int i=1;i<=n;++i)
27         scanf("%d",&x[i]);
28     sort(x+1,x+n+1);
29     int l=0,r=x[n]-x[1];
30     while(l<=r)
31     {
32         int mid=l+r>>1;
33         if(check(mid)) l=mid+1;
34         else r=mid-1;
35     }
36     printf("%d\n",r);
37     return 0;
38 }

 

· Example Two

Subject description:

  Given a length n of the sequence of positive integers A. Seeking a maximum average length of not less than L sequence.

Code:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 
 8 double a[100001],b[100001],sum[100001];
 9 
10 int main()
11 {
12     int N,L;
13     scanf("%d%d",&N,&L);
14     for(int i=1;i<=N;++i) scanf("%lf",&a[i]);
15     double eps=1e-5;
16     double l=-1e6,r=1e6;
17     while(r-l>eps)
18     {
19         double mid=(l+r)/2;
20         for(int i=1;i<=N;++i) b[i]=a[i]-mid;
21         for(int i=1;i<=N;++i) sum[i]=sum[i-1]+b[i];
22         double ans=-1e10;
23         double min_val=1e10;
24         for(int i=L;i<=N;++i)
25         {
26             min_val=min(min_val,sum[i-L]);
27             ans=max(ans,sum[i]-min_val);
28         }
29         if(ans>=0) l=mid;
30         else r=mid;
31     }
32     printf("%d",int(r*1000));
33     return 0;
34 }

 

Guess you like

Origin www.cnblogs.com/juruohqk/p/10991642.html