题解:P15267 「UTOI 1B」Chaotic Time Trio
P15267 「UTOI 1B」Chaotic Time Trio
思路
首先我们可以把非零数和零分成两组来看,然后我们要使进行若干次操作后集合中只有一个
发现两个数只有三种情况,要么是非零与非零,零与零,非零与零,非零与非零合并后的结果定然为
然后我们想,因为只有两个非零才能合并成一个零,所以我们最后一步操作时定然是两个非零合并,那么我们前面的步骤就是为了使所有数合并成两个非零数。
所以我们得知,当集合中有两个非零数的时候定然可以合并成集合中只有一个零的情况,这是为什么呢? 首先我们知道一个零和一个非零合并起来得到的是非零,所以我们可以把序列中所有的零都与非零数合并,从而定然可以得到两个非零数。
这是非零数等于二的情况,那我们题目中有若干非零数,这该怎么办呢?我们可以把里面的若干非零数通过与零数或与本身自己合并变成非零数,这里有个特判,就是如果集合中没有非零数,且
但是我们发现自己与自己合并,很有可能最后合并出来一个非零数,那么我们就需要零来参加合并,来做到一共有两个非零数,我们发现如果我们有大于等于二的零数,那么我们可以把其中两个进行合并,从而变成非零数。
这样我们就把集合中的所有数整理为了两个非零数加若干个零数,然后根据上面的两个非零数的做法就能求解出来了。
至于无解,我们发现如果我们在凑出两个非零数时凑不成功,那么定然无解,除了
Code
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=2e5+10;
int a[N];
stack<int> stk1,stk0;
pair<int,int> ans[N];
void solve(){
int n;cin>>n;
while (!stk1.empty()) stk1.pop();
while (!stk0.empty()) stk0.pop();
for (int i=1;i<=n;i++){
cin>>a[i];
if (a[i]!=0) stk1.push(a[i]);
else stk0.push(a[i]);
}
if (n==1){
if (a[1]==0) cout<<'\n';
else cout<<-1<<'\n';
return ;
}
int idx=1;
if (stk1.size()==0){
if (stk0.size()>=4){
stk1.push(1);stk1.push(1);
stk0.pop();stk0.pop();stk0.pop();stk0.pop();
ans[idx++]={0,0};
ans[idx++]={0,0};
}
else{
cout<<-1<<'\n';
return ;
}
}
while (stk1.size()>2){
int x=stk1.top();stk1.pop();
int y=stk1.top();stk1.pop();
stk0.push(0);
ans[idx++]={x,y};
}
if (stk1.size()==2){
while (!stk0.empty()){
int x=stk0.top();stk0.pop();
int y=stk1.top();stk1.pop();
if (y==1) stk1.push(2);
else stk1.push(1);
ans[idx++]={x,y};
}
int x=stk1.top();stk1.pop();
int y=stk1.top();stk1.pop();
ans[idx++]={x,y};
}
else if (stk1.size()==1){
if (stk0.size()>=2){
stk0.pop();stk0.pop();
stk1.push(1);
ans[idx++]={0,0};
while (!stk0.empty()){
int x=stk0.top();stk0.pop();
int y=stk1.top();stk1.pop();
if (y==1) stk1.push(2);
else stk1.push(1);
ans[idx++]={x,y};
}
int x=stk1.top();stk1.pop();
int y=stk1.top();stk1.pop();
ans[idx++]={x,y};
}
else{
cout<<-1<<'\n';
return ;
}
}
for (int i=1;i<idx;i++) cout<<ans[i].first<<" "<<ans[i].second<<'\n';
}
signed main(){
int T;cin>>T;
while (T--) solve();
return 0;
}