跳到正文

题解

题解:P7205 [COCI 2019/2020 #3] Drvca

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

文章信息

发布
2025年9月10日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟
题目
P7205

版本

  1. v2当前
  2. v1

先将 aa 从小到大排序。

如果有解,那么答案中一定存在一个等差数列满足其前两项为 (a1,a2),(a1,a3),(a2,a3)(a_1,a_2),(a_1,a_3),(a_2,a_3) 中的一个。考虑枚举是哪一个然后 check 是否可行。

确定了前两项 (x,y)(x,y) 后,我们就可以确定有哪些数可以存在于这个等差数列中,即找出最长的满足前两项是 (x,y)(x,y),所有数都在 aa 中的等差数列。令 b=xb=x,只需要在 aa 中扫一遍,如果此时 ai=ba_i=b,就把 aia_i 加入数列中,并令 b←b+y−xb\leftarrow b+y-x。

剩下的数就一定在另一个等差数列中。一开始的想法是直接 check 其是否为等差数列即可,但考虑以下数据:

代码
7
5 6 6 7 8 10 12
output:
3
5 6 7
4
6 8 10 12

此时 x=5,y=6x=5,y=6,如果令第一个等差数列为 5 6 7 8,那么就会剩下 6 10 12,不是等差数列。

我们发现第一个等差数列中的数可能给第二个等差数列当做“桥梁”,帮助第二个等差数列合法。那么哪些数可以用于帮助第二个等差数列呢。

由于确定了首项和公差,我们发现只能将一个后缀中的数放到第二个等差数列中去。于是我们不断的将第一个等差数列的末尾放到第二个等差数列中去,用 multiset 实时维护第二个等差数列,并用 map 记录相邻的差值。当差值只有一种时就合法输出答案即可。

时间复杂度 O(nlog⁡n)O(n\log n)。

代码:

C++
#include<bits/stdc++.h>
#define pb emplace_back
#define ll long long
#define sz(x) ((int)x.size())
#define all(x) x.begin(),x.end()
using namespace std;
const int N=1e5+10;
int n,a[N],vis[N],tot;
vector<int> s,t;
unordered_map<int,int> cnt;
void print()
{
    if(sz(s)==n)
    {
        t.pb(s.back());
        s.pop_back();
    }
    cout<<sz(s)<<"\n";
    for(auto o:s) cout<<o<<" ";
    cout<<"\n"<<sz(t)<<"\n";
    for(auto o:t) cout<<o<<' ';
    cout<<"\n";
}
inline void add(int x)
{
    cnt[x]++;
    if(cnt[x]==1) tot++;
}
inline void del(int x)
{
    cnt[x]--;
    if(!cnt[x]) tot--;
}
bool ck(int x,int d)
{
    memset(vis,0,sizeof(vis));
    cnt.clear();
    s.clear(),t.clear();
    for(int i=1;i<=n;i++)
    {
        if(a[i]==x) vis[i]=1,x+=d,s.pb(a[i]);
    }
    multiset<int> p;
    for(int i=1;i<=n;i++) if(!vis[i]) p.insert(a[i]);
    if(!sz(p)) return 1;
    tot=0;
    for(auto o=p.begin();next(o)!=p.end();o++) add(*next(o)-*o);
    if(tot<=1)
    {
        for(auto o:p) t.pb(o);
        return 1;
    }

    while(sz(s)>1)
    {
        int x=s.back();
        s.pop_back();
        auto o=p.lower_bound(x);
        if(o==p.end()) add(x-(*prev(o)));
        else{
            if(o!=p.begin()) del(*o-*prev(o)),add(x-*prev(o));
            add(*o-x);
        }
        p.insert(x);
        if(tot<=1)
        {
            for(auto o:p) t.pb(o);
            return 1;
        }
    }
    return 0;
}
int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+n+1);
    if(n==2)
    {
        cout<<1<<"\n"<<a[1]<<"\n1\n"<<a[2]<<"\n";
        return 0;
    }
    if(ck(a[1],a[2]-a[1])) print();
    else if(ck(a[1],a[3]-a[1])) print();
    else if(ck(a[2],a[3]-a[2])) print();
    else cout<<-1<<endl;
    return 0;
}
原文