[1-5] The maximum clearance issues

'Description of the problem:
the maximum gap problem: Given n real numbers n
X, X,, X 2 . 1, the n number of adjacent seeking the most number between 2 real axis
a large difference. Rounding function is assumed that any real number takes O (1), the maximum gap linear time algorithm for solving design problems.
'Programming tasks:
for a given real numbers n n
X, X,, X 2 . 1, the maximum clearance calculation program thereof.
'Input data:
the input data file by a text file called input.txt. The first line of the file has a positive integer n. The next
1 line has n real numbers n
X, X,, X 1 2 .
'The result output:
the end of the program runs, the biggest gap found in the output to a file output.txt.
Sample output file sample input file
input.txt output.txt
. 5
2.3 for 1.5 3.1 7.5 6.3
3.2

【answer】


First find the maximum and minimum coordinate difference len = maxx-minx
then minx ~ maxx this entire interval n-1 is divided into parts.
In this case, in addition to minx and max (on the n-th section maxx special treatment, minx be placed in the first fixing section) in the first and n-th interval
and the remaining n-2 will be assigned numbers 1 .. this n-1 n-1 of intervals (n th interval only the largest that number (of course, more than the maximum number does not matter))
apparently there is a range of empty!
this shows the biggest gap must be at least across a range! so do not care about the sort order for each section of the interior, as long as the recorded maximum and minimum coordinate values of the coordinate values of each interval just fine.
Then again it convenient order n-1 buckets on the line!
Beautiful!

[Code]

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

const int N = 200000;
const double INF = 1e8;

int n;
double x[N+10];
double mi = INF,ma = -INF;
double segmax[N+10],segmin[N+10],segcount[N+10];

int main(){
    //freopen("E://gap6.in","r",stdin);
    scanf("%d",&n);
    for (int i = 1;i <= n;i++){
        scanf("%lf",&x[i]);
        mi = min(mi,x[i]);
        ma = max(ma,x[i]);
    }
    //min..max 分成n-1个区间 有n-2个点会落在这n-1个区间里
    for (int i = 1;i <= n;i++){
        int idx = (int)((n-1)*(x[i]-mi)/(ma-mi)) + 1;//mi在第一个区间,ma在第n个区间
        //printf("%d\n",idx);
        if (segcount[idx]==0){
            segmax[idx] = segmin[idx] = x[i];
        }else{
            segmax[idx] = max(segmax[idx],x[i]);
            segmin[idx] = min(segmin[idx],x[i]);
        }
        segcount[idx]++;
    }
    double pre = segmax[1];double maxgap = 0;
    for (int i = 2;i<=n;i++){
        if (segcount[i]){
            if (segmin[i]-pre>maxgap){
                maxgap = segmin[i]-pre;
            }
            pre = segmax[i];
        }
    }
    printf("%.10f\n",maxgap);
    return 0;
}

Guess you like

Origin www.cnblogs.com/AWCXV/p/11617846.html