CSP Week 4 Problem C-half of the median answer to solve the problem

Overview

Before the beginning of all the problems, find out the first-half of what is very important, only half mastered the basics in order on the basis of binary algorithms, understand binary answer algorithm and solving the corresponding problem.
Because of the need to explain the dichotomy of larger space, here we introduce one next door park ultra-detailed explanation, I hope you grasp a solid first-half basis algorithm and then start Benpian reading: Here is Portal

Topic narrative

Topic Overview

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.

INPUT

Plural 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 new array ans median

SAMPLE INPUT

4
1 3 2 4
3
1 10 2

Sample Output

1
8

Restatement of the meaning of problems

The title is not abstract, very easy to understand, but more so, the pit was dug deeper
There is an array of integers, now generate an array ANS [], and which satisfies the elements satisfies:

ans[] = abs(cat[i] - cat[j])

Solving this new array of task median size, data size is 1e5

Problem-solving ideas

Perhaps the first sight of the title, you would thinkHey, this is what the title, too much water
Operators are not then the complexity, direct violence successfully started off TLE
recall violent practice, the process n points used in generating a new array O ANS [] complexity (n ^ 2) time, which in the subject 1ms within the required time is impossible. That you may be wondering how this optimization ah? ? ? ?
A difficulty: the introduction of two sub functions and determine its correctness
This time we need to introduce the dichotomy answer method to generate a complete array of computing not find the median.
After the previous study, you should understand:As long as the interval of the trend is monotonous, it can bipartite
In this title, array values can not be directly solved, so that monotonicity is not using an array of values, we need to find an indicator used in place of the array and monotonic binary Solving.
When the median is calculated array value is monotonically increasing, then the ranking in front of the element values must also be higher than the back, after this reasoning we can convert half of the array of values became the ranking of two.
But was limited by ABS () non-monotonic function, can not be directly solved ranking, we used to sort () to sort the current array guarantee monotonic, then the way to solve the rankings, which ensures that all the elements involved in the calculation has consistent monotonic, you can start using ranked-half.
Difficulties II: Solving ranking
Since the target number of columns is not known, the ranking can not be solved by traditional sequencing methods. In the algorithm process described above, each of the numbers a and solved to obtain a ranking thereof, may be substantially represented as

{P (i, j) summing | i, j satisfies xj-xi <= a}

To solve this problem, caniEnumerate, circulating, i is set as a value in solving one, A is also a constant value, which can be converted into solving algorithm satisfying the conditionsjFinally, it appears. Since the array has been ordered monotonous, we can use binary integer solver again. So far, the problem solving process all the problems are solved, the difficulty of eliminating the title.
Error-prone point
Although the difficulty of the subject has been open to our analysis, but the implementation process is easy to step on some of the pits in error-prone points. This question is to achieve first pass, the assistant may be a very painful thing, see Detailed analysis of specific parameters of the code and related Notes

int search_mid(int num)//二分答案实质:对整个答案区间进行二分查找,在不知道每个具体值的情况下,利用其他的一些推导函数(例如名次)来进行查找 
{
	int left=0;
	int right=a[num-1]-a[0];
    int mid=0;
    int ans=-1;
	int mid_pos=(num*(num-1)/2+1)/2;
    while(right>=left)
    {
    	int rank=0;
        mid=(left+right)/2; 
        for(int i=0;i<num;i++)
        {
            int flag=search_j(a[i]+mid,0,num-1);
            if(flag!=-1)
            rank+=(flag-i);
        }
        if(rank>=mid_pos)
//这里用大于等于的原因是,某个数名次等于中位数,但是实际上可能并不是中位数
//因为这里的rank找的是有多少组i-j<=p,如果找的这个P在新的数列中并不存在,他等于队列中上一个比他小的数的名次
//例如新队列 4 4 4 8 8 12,找5,6,7,得到的rank都等于3,但是其实5 6 7 都不是中位数,公式:任何一个数,只要>n,<n+1,在队列中的名次都是n 
//如果在队列 4 4 4 8 8 12中找中位数,6的rank==3,但是仍然需要向前部分找---
//根本原因:rank等于中位数的这个值在生成的数列中不一定存在,且这个值一定大于要找的中位数
//所以这里规定中位数是向下取整 
        {
            right=mid-1;
            ans=mid;
        }
        else
        left=mid+1;
    }
    return ans;
}

to sum up

After optimization of the algorithm described above, the time complexity is about O (n (logn) ^ 2), to meet the requirements of the subject. This question before the realization of dichotomy may still Bubur do not know what is half the answer; questioned how could you not know what the destination array is to find the median. After repeated study and implement the code several times, the following summary of the dichotomous answer:
The answer is a higher-order half integer variant dichotomy.
The answer is half the answer may be present within the range to generate a consistent conversion of monotonic parameters, continuous binary ultimately find out the answer
Specific implementation templates:
topic dichotomous answers, often the target array is not seeking or obtaining time out, that is not an integer-half of the target range. We have to solve is to find indicators of a resort within the time limit complexity instead of the target range, thus completing the half. After identify the indicators, methods dichotomy is the answer as the lower limit of the upper and lower half of the all the elements in the area to find and binary processing, finally found the answer.

Source title

#include<iostream>
#include<cstdio>
#include <algorithm>
using namespace std;
int a[100001];
int search_j(int find_b,int left,int right)//找到j点(小于等于find_b的最后一个点)
{
    int ans=-1;
    int mid=0;
    while(left<=right)
    {
        mid=(left+right)/2;
        if(a[mid]<=find_b)
        {
            ans=mid;
            left=mid+1;
        }
        else
        right=mid-1;
    }
    return ans;
}
int search_mid(int num)
{
	int left=0;
	int right=a[num-1]-a[0];
    int mid=0;
    int ans=-1;
	int mid_pos=(num*(num-1)/2+1)/2;
    while(right>=left)
    {
    	int rank=0;
        mid=(left+right)/2; 
        for(int i=0;i<num;i++)
        {
            int flag=search_j(a[i]+mid,0,num-1);
            if(flag!=-1)
            rank+=(flag-i);
        }
        if(rank>=mid_pos)
        {
            right=mid-1;
            ans=mid;
        }
        else
        left=mid+1;
    }
    return ans;
}
int main()
{
    int number=0;
    while(scanf("%d",&number)!=EOF)
    {
    for(int i=0;i<number;i++)
    {
        scanf("%d",&a[i]);
    }
    sort(a,a+number);
    int result=search_mid(number);
    cout<<result<<endl;
    }
    return 0;
}
Published 17 original articles · won praise 2 · Views 1659

Guess you like

Origin blog.csdn.net/qq_43942251/article/details/104980325