Seeking the maximum and minimum divide and conquer

Description

Given the number of n, with 3n / 2-2 comparisons to find the minimum and maximum values ​​of the n number of elements in the worst case.

Required to write only function 

void maxmin(int a[],int low,int high,int *max,int *min).

系统会自动在程序的最后加上如下代码:

int main()
{
    int max,min,k,a[200];
    int m;
    while(scanf("%d",&k)&&k)
    {
        for(m=0;m<k;m++)
            scanf("%d",&a[m]);
        maxmin(a,0,k-1,&max,&min);
        printf("%d %d\n",max,min);
   
    }
} 

Input

Multiple sets of test data. The first element of each test is an integer number n, followed by n integers. 0 indicates the end. n <= 200

Output

This maximum and minimum values ​​of the number n.

Sample Input

5 1 8 2 4 3
3 2 4 1
0

Sample Output

1 8 
4 1 


If you need to compare before traversing over n-1 times to get the maximum and minimum values in the array, which is obviously not in line with expectations, there should be used divide and conquer idea.
Divide and conquer there are three main steps:
1. decomposition: the original problem is divided into several smaller sub-problems.
2. Solving: sub-problems small enough to be solved, and went to solve it.
3. Merge: The solution of the problem of child merged into solution of the original problem.

For this problem it is constantly a half, until a decomposition inseparable array element, the array element is the maximum a minimal problem is the minimum, then combined into one by one solution to the original problem.
#include<cstdio>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;

void maxmin(int *a,int left,int right,int *max,int *min)
{
    int mid;
    int lmax=0,lmin=inf,rmax=0,rmin=inf;
    if(left==right)
    {
        *max=a[left];
        *min=a[right];
        return ;
    }
    mid=(left+right)/2;
    maxmin(a,left,mid,&lmax,&lmin);
    maxmin(a,mid+1,right,&rmax,&rmin);
    if(lmax>rmax)
    {
        *max=lmax;
    }
    else
    {
        *max=rmax;
    }
    if(lmin<rmin)
    {
        *min=lmin;
    }
    else
    {
        *min=rmin;
    }
}
int main()
{
    int max,min,k,a[200];
    int m;
    while(scanf("%d",&k)&&k)
    {
        for(m=0; m<k; m++)
            scanf("%d",&a[m]);
        maxmin(a,0,k-1,&max,&min);
        printf("%d %d\n",max,min);
    }

}

 

Guess you like

Origin www.cnblogs.com/wkfvawl/p/11460280.html