P10830 题解

· · 题解

我们充分发扬人类智慧:

发现题目中“每次选出的两个数之和必须是偶数”的限制非常弱,考虑随机化。

具体地,每次选出任意一对奇偶性相同的数进行操作,直到无法操作为止,此时如果只剩下一个数就做完了。为了方便实现,将初始的 a_i 打乱之后放进两个栈里面,每次从栈顶取两个数,操作之后再压回栈内。重复 K=400 次即可通过。

时间复杂度 O(Kn)。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=1000007;
ll T,n,a[N];
vector<ll> s[2];
vector<pair<ll,ll> > ans;
mt19937 rng(20120712);
ll get(vector<ll>& vec){
    auto x=vec.back();vec.pop_back();return x;
}
bool solve(){
    s[0].clear();s[1].clear();ans.clear();
    shuffle(a+1,a+1+n,rng);
    for (int i=1;i<=n;++i) s[a[i]&1].emplace_back(a[i]);
    for (int i=n-1;i;--i){
        if (s[0].size()<2&&s[1].size()<2) return 0;
        ll x,y,d=rng()&1;
        if (s[d].size()<2) d^=1;
        x=get(s[d]);y=get(s[d]);
        ans.emplace_back(x,y);
        d=x+y>>1;
        s[d&1].emplace_back(d);
    }
    for (auto p:ans) cout<<p.first<<' '<<p.second<<'\n';
    return 1;
}
int main(){
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    cin>>T;
    while(T--){
        cin>>n;
        for (int i=1;i<=n;++i) cin>>a[i];
        bool fl=1;
        for (int _=1;_<=400;++_) if (solve()){
            fl=0;break;
        }
        if (fl) cout<<"-1\n";
    }
    return 0;
}