题意
给定一个数组,可通过若干次在任意位置添加两个相同数的操作,使该数组能够被拆分成若干个平方串,其中如 “ 1321324545 ” “1321324545” “1321324545” 即可拆为两个平方串,而 “ 135531 ” “135531” “135531” 则不是(该概念可类比于周期函数)。并输出操作的次数及每一次操作在什么位置插入了什么数,以及最终组成的若干个平方串分别的长度,如 “ 1321324545 ” “1321324545” “1321324545” 的长度分别为 6 6 6 和 4 4 4。
分析
由于本题中每次插入都是两个相同的数,而由平方串的性质可得,其中的每个数字一定是以偶数出现的,因此对于需要输出 “ − 1 ” “-1” “−1” 的情况,不难发现是给定的数组中存在出现了奇数次的数。
在构造过程中可发现,例 “ 13241243 ” “13241243” “13241243” ,成功构成 “ 1324 ” “1324” “1324” 后得到的数组为 “ 13241324 “13241324 “13241324 423 423 423 243 ” 243” 243”,其中中间部分的 “ 423 ” “423” “423” 即为原数组中两个 1 1 1 之间子段的倒置。得到这个规律后可以通过记录坐标从而免去在数组中插入的操作。
因此 “ 13241 ” “13241” “13241” 在操作完后可转置为 “ 11423 ” “11423” “11423” ,同时下标 + 2 +2 +2 指向下一个待匹配的数。但由于每次的插入操作都需要明确指定位置,因此可用 l a s t last last 记录之前理应匹配成功后的长度,并通过对应关系推出真实的位置。
参考代码
#include<bits/stdc++.h>
#define int long long
#define PII pair<int,int>
using namespace std;
const int N = 505;
int a[N],tmp[N],n;
map<int,int> mp;
vector<int> v;
vector<PII> ans;
void solve(){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
mp.clear();
for(int i=1;i<=n;i++)
mp[a[i]]++;
bool flag = 1;
for(PII p:mp){
if(p.second%2==1){
flag=0;
break;
}
}
if(!flag){
cout<<"-1\n";
return ;
}
v.clear();
ans.clear();
int now=1,last=0;
while(now<=n){
int index=-1;
for(int i=now+1;i<=n;i++){
if(a[i]==a[now]){
index=i;
break;
}
}
v.push_back((index-now)*2);//该子段配置完毕后的长度贡献
for(int i=now+1;i<index;i++)
ans.push_back({last+index-now+i-now,a[i]});
for(int i=now+1;i<index;i++)
tmp[i]=a[index-(i-now)];
for(int i=now+2;i<=index;i++)
a[i]=tmp[i-1];
//以上操作为进行数组内的子段倒置
last+=(index-now)*2;//最后一组配对完后的下标
now+=2;//下一个待构造
}
cout<<ans.size()<<endl;
for(auto p:ans)
cout<<p.first<<" "<<p.second<<endl;
cout<<v.size()<<endl;
for(auto val:v)
cout<<val<<" ";
cout<<endl;
}
signed main(){
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}