题面
https://www.luogu.org/problem/CF1031D
题解
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; const int dx[]={0,1},dy[]={1,0}; char map[2050][2050],mx,mn; bool vis[2050][2050]; int n,k,f[2050][2050],maxstep,nowl,x0,y0,nx,ny; struct node{ int pre,x,y,l; } que[8500500]; string nows; void solve (int p) { string ans=""; while (p!=-1) { ans.push_back(map[que[p].x][que[p].y]); p=que[p].pre; } int l=ans.size(),i; for (i=l-1;i>=0;i--) cout<<ans[i]; exit(0); } int main(){ int i,j,ii,head,tail; ios::sync_with_stdio(false); cin>>n>>k; for (i=1;i<=n;i++) for (j=1;j<=n;j++) cin>>map[i][j]; if (n==1 && k==0) { cout<<map[1][1]<<endl; return 0; } f[1][1]=(map[1][1]=='a'); for (i=2;i<=n;i++) f[1][i]=f[1][i-1]+(map[1][i]=='a'); for (i=2;i<=n;i++) f[i][1]=f[i-1][1]+(map[i][1]=='a'); maxstep=0; for (i=2;i<=n;i++) for (j=2;j<=n;j++) f[i][j]=max(f[i-1][j],f[i][j-1])+(map[i][j]=='a'); maxstep=0; for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (f[i][j]+k>=i+j-1) maxstep=max(maxstep,i+j-1); //cout<<maxstep<<endl; for (i=1;i<=maxstep;i++) cout<<'a'; if (maxstep==2*n-1) return 0; head=1; tail=0; mn=(char)((int)'z'+1); for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (f[i][j]+k==maxstep && i+j-1==maxstep) { for (ii=0;ii<=1;ii++) { nx=i+dx[ii]; ny=j+dy[ii]; if (nx<=n && ny<=n && map[nx][ny]<=mn && (!vis[nx][ny])) { vis[nx][ny]=true; mn=map[nx][ny]; que[++tail]=(node){-1,nx,ny,1}; if (ny==n && nx==n) solve(tail); } } } if (maxstep==0) {tail++; que[1]=(node){-1,1,1,1};} while (head<=tail) { x0=que[head].x; y0=que[head].y; if (que[head].l==que[head-1].l+1) {mx=mn; mn=(char)((int)'z'+1);} if (map[x0][y0]>mx) {head++; continue;} for (ii=0;ii<=1;ii++) { nx=x0+dx[ii]; ny=y0+dy[ii]; if (nx<=n && ny<=n && map[nx][ny]<=mn && (!vis[nx][ny])) { vis[nx][ny]=true; mn=map[nx][ny]; que[++tail]=(node){head,nx,ny,que[head].l+1}; if (ny==n && nx==n) solve(tail); } } head++; } }