没听懂 dottle 的讲课时讲的,QQ 上搞懂后来造福后人。
Solution
注意到朴素的启发式合并是 的。无法通过,考虑使用 分块。 将序列每 个分块,所以一共有 种块,将所有块按种类分组。
关于一种块,你将它所有出现位置记录下来了,然后对出现这种块的第一个出现 位置进行启发式合并。
为什么这么做呢,启发式合并完后,我们可以通过平移这个得到的集合,使这种块的每个 位置都有覆盖。

如图所示,我们设 为 ,我们发现第 个块属于同一种块,我们对于这种块第一个出现 位置,即一号位置进行合并,就是将图上 号位置进行合并,我们通过平移该集合,可以得到图中 号位置,这样我们就创造出这种块所需所有集合。再进行启发式合并一下,这种块的集合就求到了。
接着,将每种块的集合启发式合并即可。
再来分析一下所需集合大小。
对于每种块,启发式合并出其起始位置的集合是 的,再用 操作平移,然后用 操作合并是 。
把各种类型的块合并到一起又是 。
取 可以达到 的复杂度。
code
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
const int N=5e6+9,B=4;
char s[N];
int cnt=0;
struct node{
int opt,x,y;
}e[N];
vector<int> vv[N];
int ss[N],lenn[N];
void merge(int u)
{
if(vv[u].empty()) return ;
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>> > q;
for(int v:vv[u])
{
// cout<<v<<"!";
q.push({1,++cnt});
e[cnt]={1,v,0};
}
while(q.size()!=1)
{
int u1=q.top().second,len1=q.top().first;
q.pop();
int u2=q.top().second,len2=q.top().first;
q.pop();
q.push(make_pair(len1+len2,++cnt));
e[cnt]={2,u1,u2};
}
int len=q.top().first,pos=cnt;
q.pop();
for(int j=1;j<=B;j++)
{
if(u&(1<<(j-1)))
{
q.push({len,++cnt});
e[cnt]={3,pos,j-1};
}
}
while(q.size()!=1)
{
int u1=q.top().second,len1=q.top().first;
q.pop();
int u2=q.top().second,len2=q.top().first;
q.pop();
q.push(make_pair(len1+len2,++cnt));
e[cnt]={2,u1,u2};
}
ss[u]=cnt;
lenn[u]=q.top().first;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
cin>>(s+1);
for(int i=1;i<=n;i+=B)
{
int vall=0;
for(int j=1;j<=B;j++)
{
if(s[j+i-1]=='1')
vall+=(1<<(j-1));
}
// cout<<vall<<"!!!!!";
vv[vall].push_back(i);
}
for(int i=1;i<(1<<B);i++)
{
merge(i);
}
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>> > q;
for(int i=1;i<(1<<B);i++)
{
if(ss[i]!=0)
{
q.push({lenn[i],ss[i]});
}
}
while(q.size()!=1)
{
int u1=q.top().second,len1=q.top().first;
q.pop();
int u2=q.top().second,len2=q.top().first;
q.pop();
q.push(make_pair(len1+len2,++cnt));
e[cnt]={2,u1,u2};
}
cout<<cnt<<endl;
for(int i=1;i<=cnt;i++)
{
if(e[i].opt==1)
{
cout<<1<<" "<<e[i].x<<endl;
}
else
cout<<e[i].opt<<" "<<e[i].x<<" "<<e[i].y<<endl;
}
return 0;
}