洛谷P8148题解

本文同步更新于洛谷博客

题目描述

\(a\) 为长度为 \(n\) 的非负整数序列,满足 \(\forall 1<i\le n,a_{i-1}\le a_i\)。现无序地给出可重\(S=\{\sum_{k=l}^ra_k|1\le l\le r\le n\}\),试还原 \(a\)

题解

先声明一下,\(a\) 为给定的序列,\(b\) 为还原后的 \(a\)\(c_{i,j}\)\(\sum_{k=i}^jb_k\)\(s\) 为 STL 容器 multiset,下述区间的长度均大于 \(1\)
由于给定的数是无序的,所以先对 \(a\) 排序。若 \(a_i\)\(s\) 中出现过,则它为 \(b\) 某一段区间的和,将其从 \(s\) 中删掉即可;若 \(a_i\) 没在 \(s\) 中出现过,不妨假设 \(b_j=a_i\),我们将所有以 \(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;
}
posted @ 2022-02-12 22:08  Ginger_he  阅读(72)  评论(0)    收藏  举报