题解:P15267 「UTOI 1B」Chaotic Time Trio

· · 题解

这题的 corner 很多,本蒟蒻太弱了,交了好几发才过。

分析

可以先打表,找到一些特殊情况,然后我们可以发现做法。

由于 \operatorname{mex} 的特殊性质,我们可以将数字分成 0 和非零数,我们发现 2 个非零数可以合成一个 0,不妨我们可以尽可能将非零数合成很多 0。

然后我们发现只可能剩下 1 个非零数或 2 个非零数。如果剩下 1 个非零数,我们可以将 2 个 0 合成一个非零数,然后按照有 2 个非零数的情况进行处理。

最后,用 1 个非零数消去前面的所有 0 即可。

代码

#include<bits/stdc++.h>
#define int long long
#define F(i,l,r,x) for(int i=(l);i<=(r);i+=(x))
#define D(i,r,l,x) for(int i=(r);i>=(l);i-=(x))
#define DB1(x) cout<<#x<<' '<<(x)<<' '
#define DB2(x) cout<<#x<<' '<<(x)<<'\n'
using namespace std;
const int N=2e5+5,MOD=1e9+7;
int T,n;
int a[N];
int mex(int a,int b) {
    for(int i=0; i<=2; i++) {
        if(i!=a&&i!=b)return i;
    }
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>T;
    while(T--) {
        int cnt0=0,cnt1=0;
        deque<int> v0,v1;
        cin>>n;
        F(i,1,n,1) {
            cin>>a[i];
            if(a[i]>0)cnt1++,v1.push_back(a[i]);
            else cnt0++,v0.push_back(a[i]);
        }
        bool f=0;
        if(!cnt0) {
            if(cnt1==1||cnt1==3)f=1;
        }
        if(!cnt1) {
            if(cnt0==2||cnt0==3)f=1;
            else if(cnt0==1)continue;
        }
        if(cnt0==1&&cnt1==1)f=1;
        if(f) {
            cout<<-1<<'\n';
            continue;
        }
        if(v1.empty()) {
            cout<<0<<' '<<0<<'\n';
            v0.pop_front(),v0.pop_front();
            v1.push_back(1);
        }
        while(v1.size()>=3) {
            int tmp1=v1.front();
            v1.pop_front();
            int tmp2=v1.front();
            v1.pop_front();
            cout<<tmp1<<' '<<tmp2<<'\n';
            v0.push_back(0);
        }
        if(v1.size()&1) {
            cout<<0<<' '<<0<<'\n';
            v0.pop_front(),v0.pop_front();
            v1.push_back(1);
        }
        while(!v0.empty()) {
            int tmp1=v1.front();
            v1.pop_front();
            int tmp2=v0.front();
            v0.pop_front();
            cout<<tmp1<<' '<<tmp2<<'\n';
            v1.push_front(mex(tmp1,tmp2));
        }
        int tmp1=v1.front();
        v1.pop_front();
        int tmp2=v1.front();
        v1.pop_front();
        cout<<tmp1<<' '<<tmp2<<'\n';
    }
    return 0;
}