week4 job C

Meaning of the questions:
TT is a severe cat lovers, cat channel on the daily indulge in B station.
One day, a friend ZJM decided to TT TT a problem, if TT can solve this problem, ZJM will buy a cute cat gave TT.
SUMMARY is given array cat [i] a number N, and generate a new array ans [i] with the array. It is defined as the new array for any i, j and i = j, are ans [] = abs (cat [ i] - cat [j])!, 1 <= i <j <= N. This new array. Determine the median, then the median is the sort (len + 1) / 2 corresponding to the position number, '/' is a rounding.
TT desperately wanting bird cute cat, can you help him?
input:
multiple sets of inputs, each input one N, the number N expressed, after the input of a sequence of length N CAT, CAT [I] <= 1E9,. 3 <= n-<= 1E5
Output:
output ans the new array median
Sample iNPUT:
. 4
. 1. 3 2. 4
. 3
. 1 10 2
Sample Output:
. 1
. 8
ideas:
enter the number of columns, the number of columns for sorting. Understood meaning of the questions, the maximum number of a [n-1] -a [ 0]. Median position (n * (n-1) / 2 + 1) / 2. Enumeration divided by two, because the median total number of positions in the middle, so that the number is smaller than the median number should be equal to the number greater than the number less than the median. Constantly compare to find through this method, we can obtain the value of the median final.
Code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
int a[100050];
int find(int x,int n)
{
 int l=0,r=n-1,ans=-1;
 while(l<=r)
 {
  int mid=(l+r)>>1;
  if(a[mid]>=x)
  {
   ans=mid;
   r=mid-1;
  }
  else if(a[mid]<x) 
  {
   l=mid+1;
  }
 }
 if(ans==-1)
 {
  ans=n;
    } 
 return ans;
}
int main()
{
 int n; 
 while(cin>>n)
 {
  for(int i=0;i<n;i++)
  {
   scanf("%d",&a[i]);
   //cin>>a[i];
  }
  sort(a,a+n);
  int r=a[n-1]-a[0];
  int l=0;
  int cm=(n*(n-1)/2+1)/2;
  while(l<=r)
  {
   int mid=(l+r)>>1;
   int count=0;
   for(int i=0;i<n;i++)
   {
    count=count+n-find(a[i]+mid,n); 
   }
   if(count>(n*(n-1)/2-cm))
   {
    l=mid+1;
    } 
   else 
   {
    r=mid-1;
   }
  }
  cout<<r<<endl;
 }
 return 0;
}
Published 19 original articles · won praise 0 · Views 209

Guess you like

Origin blog.csdn.net/weixin_45117273/article/details/104983938