跳到正文

题解

题解 P1090 【合并果子】

yyy2015c01约 5 分钟
原文
文章信息与版本

文章信息

发布
2015年6月30日
收录
2026年4月6日
更新
2026年11月14日
篇幅
约 5 分钟
题目
P1090

版本

  1. v2当前
  2. v1

内容摘自:http://y.luogu.org/

题解

一个很经典的题目。

我的方法是每次选取最少的两堆合并,直到剩一堆。

然而这样,每次都要排序以确定最少果子的两堆,代码复杂度、时间复杂度和空间复杂度都要上升。

作为一个使用C++的OIer,自然就想到了STL(要查看更多与STL有关的内容,请到:术语集合)。

需要#include<queue>以使用优先队列。

AC代码:

C++
#include<queue>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
using namespace std;
int main()
{
    priority_queue<int>gz;  //优先队列
    int n;
    scanf("%d",&n);
    for (int i=1,temp;i<=n;i++)
    {
        scanf("%d",&temp);
        gz.push(-temp);  //为了按从小到大排序
    }
    int hb=0;
   for (int i=1,temp=0;i<n;i++)  //合并最小的两堆
   {
        temp=gz.top();  //temp负责计算两堆合并后的果子数
        hb-=gz.top();
        gz.pop();
        temp+=gz.top();
        hb-=gz.top();  //hb负责计算体力
        gz.pop();
        gz.push(temp);
   }
   printf("%d",hb);  //输出
}

但是!还有但是!当时C++不允许使用STL(否则有语言歧视嫌疑)!所以,我们要提升能力,就不要使用STL。

步骤:

读进数组

排序 取a,b(b开始为空,初始化为近似无穷大,但要使得“无穷大”+“无穷大”=“无穷大”*2,而不会溢出成为负数)

取a,b中最小的两个数合并,存在b数组后面,相加的两个数删掉。这两个数的和累加到体力中。该步重复n-1次。

输出体力

AC*2代码:

C++
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<cctype>
#include<iostream>
using namespace std;
int a[100001],b[100000],al=0,ar,bl=0,br=0,tl=0;
void pd()
{
    if((a[al]+a[al+1] < a[al]+b[bl])&& (a[al]+a[al+1] < b[bl]+b[bl+1]))
    {
        b[br]=a[al]+a[al+1];
        al+=2;
    }
    else
    {
        if (a[al]+b[bl] < b[bl]+b[bl+1])
        {
            b[br]=a[al]+b[bl];
            bl++;
            al++;
        }
        else
        {
            b[br]=b[bl]+b[bl+1];
            bl+=2;
        }
    }
    tl+=b[br];
    br++;
}
int main()
{
    memset(a,0x3f3f3f3f,sizeof(int)*100001);
    memset(b,0x3f3f3f3f,sizeof(int)*100000);
    int n;
    scanf("%d",&n);
    for (int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    ar=n-1;
    int i=1;
    bool jh=false;
    do
    {
        jh=false;
        for (int j=1;j<=n-i;j++)
        {
            if (a[j-1]>a[j])
            {
                a[100000]=a[j-1];
                a[j-1]=a[j];
                a[j]=a[100000];
                jh=true;
            }
        }
        i++;
    }
    while(jh);
    for (int i=1;i<n;i++)
    {
        pd();
    }
    printf("%d",tl);
}

[color=red]注:该程序冒泡排序还可改为更优的快速排序,请读者自行思考。[/color]

STL与非STL代码比较

STL 非STL

代码长度 0.43KB 0.88KB

单店平均运行时间 6ms 118ms

单店平均消耗内存 2042kb 2848kb

我不禁感叹STL是多么好用啊~233

--------------------------------------------The End-----------------------------------------

原文