【一句话题意】有多种操作
1、删除一个字符,代价为1
2、加入一个字符,代价为1
3、复制字符串为原来的k倍,代价为2+2*k
3、删除所有字符,代价为3
现在有初始长度为x,求到长度n最小代价。
【分析】
题目稍作简化,请无视。
显然删除所有字符只有在所有操作之前(反证法即可)。
稍作思考即可发现,dp值的大小,存在极强的后效性。所以,改成最短路求dist[x],spfa玄学复杂度再加常数优化。
【code】
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define rint register int
using namespace std;
const int maxn=1e6+1000;
int dist[maxn<<1];
bool inq[maxn<<1];
struct Queue{
int a[maxn<<1];
int l,r;
bool empty(){return l==r;}
void push(int x){a[r++]=x;r%=maxn<<1;}
int front(){return a[l];}
void pop(){l++;l%=maxn<<1;}
}q;
int main(){
freopen("keyboard.in","r",stdin);
freopen("keyboard.out","w",stdout);
// queue<int>q;
rint x,n;
cin>>x>>n;
memset(dist,0x3f,sizeof(dist));
dist[0]=3,dist[x]=0;
inq[0]=1,inq[x]=1;
q.push(0),q.push(x);
while(!q.empty()){
rint x=q.front();q.pop();inq[x]=0;
if(x){
for(rint i=2;i*x<=(n<<1);i++){
if(dist[i*x]>dist[x]+(i<<1)+2){
dist[i*x]=dist[x]+(i<<1)+2;
if(!inq[i*x]) inq[i*x]=1,q.push(i*x);
}
}
}
for(rint i=x-1;i>=0;i--){
if(dist[i]<=dist[x]+(x-i)) break;
dist[i]=dist[x]+(x-i);
if(!inq[i]) inq[i]=1,q.push(i);
}
for(rint i=x+1;i<=(n<<1);i++){
if(dist[i]<=dist[x]+(i-x)) break;
dist[i]=dist[x]+(i-x);
if(!inq[i]) inq[i]=1,q.push(i);
}
}
cout<<dist[n]<<endl;
return 0;
}