Let life be beautiful |

Ginger_he

园龄:3年1个月粉丝:5关注:5

洛谷P8148题解

本文同步更新于洛谷博客

题目描述

a 为长度为 n 的非负整数序列,满足 1<in,ai1ai。现无序地给出可重S={k=lrak|1lrn},试还原 a

题解

先声明一下,a 为给定的序列,b 为还原后的 aci,jk=ijbks 为 STL 容器 multiset,下述区间的长度均大于 1
由于给定的数是无序的,所以先对 a 排序。若 ais 中出现过,则它为 b 某一段区间的和,将其从 s 中删掉即可;若 ai 没在 s 中出现过,不妨假设 bj=ai,我们将所有以 j 结尾的 b 的区间和放入 s 中即可。

注意

  • 给定的数中可能有重复,所以要用 multiset。
  • multiset 的 erase 要删除其指针。
  • multiset 的常数很大,卡卡常就行了。

Code

#include<bits/stdc++.h>
using namespace std;
#define rint register int
const int maxn=2001005;
inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
int n,m,x,a[maxn],b[2005],c[2005],cnt;
multiset<int> s;
multiset<int>::iterator pos;
int main()
{
    n=read();
    m=n*(n+1)/2;
    for(rint i=1;i<=m;i++)
        a[i]=read();
    sort(a+1,a+m+1);
    for(rint i=1;i<=m;i++)
    {
        if(s.count(a[i]))
        {
            pos=s.find(a[i]);
            s.erase(pos);
        }
        else
        {
            b[++cnt]=a[i];
            for(rint j=1;j<cnt;j++)
                s.insert(c[j]+=b[cnt]);
            c[cnt]=b[cnt];
            if(cnt==n)
                break;//这个优化很重要
        }
    }
    for(rint i=1;i<=n;i++)
        printf("%d ",b[i]);
    return 0;
}

本文作者:Ginger_he

本文链接:https://www.cnblogs.com/Gingerhe/p/15887615.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ginger_he  阅读(55)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起