Divide and Conquer -1平均的奶牛

FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' cow gives: half of the cows give as much or more than the median; half give as much or less. Given an odd number of cows N (1 <= N < 10,000) and their milk output (1..1,000,000), find the median amount of milk given such that at least half the cows give the same amount of milk or more and at least half give the same or less.

题目大意:FJ 正在调查他的牛群,以找出最平均的奶牛。他想知道这头 "中位数 "奶牛的产奶量:一半奶牛的产奶量与中位数相当或更高;一半奶牛的产奶量与中位数相当或更低。给定奇数头奶牛 N(1 <= N < 10,000)和它们的产奶量(1...1,000,000),求奶牛产奶量的中位数,使得至少一半奶牛产奶量相同或更多,至少一半奶牛产奶量相同或更少。

作者声明,此博客作者自用于复习。抄作业的同学们手下留情。不是伪代码,但是是伪英语

Obviously this question needs to be solved using a sorting method to order the data and then find the median, and then looking at the title as a partition, then use a subsumption sort and a quick sort to solve the problem, let's review the templates for the two types of sorts next.

QuickSort 

void quickSort(int a[],int l,int r)
{
    if(l>=r) return ;
    int i=l-1,j=r+1,mid=l+r>>1;
    int x = a[mid];
    while(i<j)
    {
        do i++;
        while(a[i]<x);
        do j--;
        while(a[j]>x);
        if(i<j)
        swap(a[i],a[j]);
    }
    quickSort(a,l,j);
    quictskSort(a,j+1,r);
//Thoughs:
//First when the l>r,it stands that the l has missed the r;then return;
//Second let i=l-1,j=r+1,for the do-while. To make the i<mid&&a[i]<x and j>mid && a[j]>x
//if both i and j break the cycle && i<j stands for that the to need to swap
//Third recursive processing of the left and right halves of an array
}

MergeSort

const int N=1e6+10;
int ans[N];
void mergeSort(int a[],int l,int r)
{

    if(l>=r)return;
    int i=l,j=r,k=0,mid=l+r>>1;
    mergeSort(a,l,mid)
    mergeSort(a,mid,r);
    while(i<=mid&&j<=r)
    {
        if(a[i]<a[j])
            ans[k++]=a[i++];
        else
            ans[k++]=a[j++];
    }
    while(i<=mid)
     ans[k++]=a[i++];
    while(j<=r)
     ans[k++]=a[j++];

    for(int i=l,j=0;i<=r;i++,j++)
    {
        a[i]=ans[j];    
    }
//Thoughts:
//First divide the array into two parts for recursive processing
//Then each of the two parts is traversed starting with the minimum value, and whichever //side is smaller is put into the ans array
//Finally, assign the value of the ans array to the a array
}

 Main

int main()
{
    int n;
    cin >> n;
    int a[N];
    for(int i=0;i<n;i++)
    {
     cin>>a[i];   
    }    
mergeSort(a,0,n-1);
cout<<a[n-1>>1]<<endl;
    return 0;
}

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熟人看不到

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值