题意:
思路:
用可返回堆即通过双向链表和小根堆(可以用STL的优先队列)实现.
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll inf=1e9+7;
char s[1000005], t[1000005];
int head=-1, pre[1000005], Next[1000005], val[1000005], ji=1, L[1000005], R[1000005];
struct w
{
int v, val, l, r;
} w, w2;
struct qu
{
int l, r;
}jian[1000005];
bool operator < (struct w a,struct w b)
{
return a.val>b.val;
}
bool cmp(struct qu a,struct qu b)
{
return a.r-a.l>b.r-b.l;
}
int main()
{
int n, k, jj=0;
scanf("%d%d",&n,&k);
cin >> s;
if(n==1)
{
printf("0\n");
cout << s << endl;
return 0;
}
for(int i=1; i<n; i++)
{
val[ji]=(s[i]!='c')+(s[i-1]!='a');
L[ji]=i-1;
R[ji]=i;
pre[ji]=-1;
Next[ji]=head;
if(head!=-1)
pre[head]=ji;
head=ji;
ji++;
}
priority_queue<struct w> q;
ll ans=0;
for(int i=head; i!=-1; i=Next[i])
{
w.v=i;
w.val=val[i];
w.l=i-1;
w.r=i;
q.push(w);
}
//printf("%d\n",q.size());
while(1)
{
w.v=-1;
while(!q.empty()&&(w.v==-1||val[w.v]==-1))
{
w=q.top();
q.pop();
}
if(q.empty()&&(w.v==-1||val[w.v]==-1))
{
break;
}
if(k>=w.val)
{
ans++;
jian[jj].l=w.l;
jian[jj++].r=w.r;
k=k-w.val;
}
else
{
break;
}
//printf("%d %d\n",w.v,ans);
if(pre[w.v]!=-1&&Next[w.v]!=-1)
{
w2.v=ji;
w2.val=val[pre[w.v]]+val[Next[w.v]]-val[w.v];
val[ji]=w2.val;
w2.r=max(R[pre[w.v]],R[Next[w.v]]);
w2.l=min(L[Next[w.v]],L[pre[w.v]]);
L[ji]=w2.l;
R[ji]=w2.r;
val[pre[w.v]]=-1;
val[Next[w.v]]=-1;
pre[ji]=pre[pre[w.v]];
if(pre[pre[w.v]]==-1)
{
head=ji;
}
else
{
Next[pre[pre[w.v]]]=ji;
}
Next[ji]=Next[Next[w.v]];
if(Next[Next[w.v]]!=-1)
{
pre[Next[Next[w.v]]]=ji;
}
ji++;
q.push(w2);
}
else if(pre[w.v]==-1&&Next[w.v]!=-1)
{
val[Next[w.v]]=-1;
head=Next[Next[w.v]];
if(Next[Next[w.v]]!=-1)
{
pre[Next[Next[w.v]]]=-1;
}
}
else if(pre[w.v]!=-1&&Next[w.v]==-1)
{
val[pre[w.v]]=-1;
if(pre[pre[w.v]]==-1)
{
head=-1;
}
else
{
Next[pre[pre[w.v]]]=-1;
}
}
else
{
//printf("%d\n",q.size());
head=-1;
}
}
sort(jian,jian+jj,cmp);
for(int i=0;i<=n;i++)
{
t[i]='\0';
}
for(int j=0;j<jj;j++)
{
//printf("l=%d r=%d\n",jian[j].l,jian[j].r);
if(t[jian[j].l]=='\0')
{
for(int o=jian[j].l;o<=jian[j].r;o=o+2)
{
t[o]='a';
t[o+1]='c';
}
}
}
for(int i=0;i<n;i++)
{
if(t[i]=='\0')
{
t[i]=s[i];
}
}
cout << ans << endl;
cout << t << endl;
}