#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define rng(i,c,n) for(int i=c;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define fi first
#define se second
#define pb push_back
#define sz(a) (int)a.size()
#define vec(...) vector<__VA_ARGS__>
#define _3phCa4T ios::sync_with_stdio(0),cin.tie(0)
typedef long long ll;
using pii=pair<int,int>;
using vi=vector<int>;
void print(){cout<<'\n';}
template<class h,class...t>
void print(const h&v,const t&...u){cout<<v<<' ',print(u...);}
// e
const int di[]={1,0};
const int dj[]={0,1};
signed main(){
_3phCa4T;
int h,w;
cin>>h>>w;
vec(vec(char)) a(h,vec(char)(w));
rep(i,h){
rep(j,w){
cin>>a[i][j];
}
}
using T=pair<int,pii>;
vec(vec(T)) dp(h,vec(T)(w,T(0,pii(-1,-1))));
dp[0][0]={1,{-1,-1}};
queue<pii> que;
que.push(pii(0,0));
rep(_,h+w){
char ch='z';
vec(pair<pii,pii>) delay;
while(sz(que)){
auto top=que.front();
que.pop();
int i=top.fi,j=top.se;
rep(dir,2){
int ni=i+di[dir],nj=j+dj[dir];
if(ni<0 or nj<0 or ni>=h or nj>=w) continue;
delay.pb({pii(ni,nj),pii(i,j)});
ch=min(ch,a[ni][nj]);
}
}
for(auto fp:delay){
pii p=fp.fi,q=fp.se;
int i=p.fi,j=p.se;
if(a[i][j]==ch and dp[i][j].fi==0){
dp[i][j].fi=1;
dp[i][j].se=q;
que.push(pii(i,j));
}
}
}
assert(dp[h-1][w-1].fi);
int i=h-1,j=w-1;
vec(char) pns;
while(i>=0){
pns.pb(a[i][j]);
int ni=dp[i][j].se.fi;
int nj=dp[i][j].se.se;
i=ni,j=nj;
}
reverse(pns.begin(), pns.end());
for(auto ch:pns){
cout<<ch;
}
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Correct |
0 ms |
340 KB |
Output is correct |
3 |
Correct |
1 ms |
212 KB |
Output is correct |
4 |
Correct |
0 ms |
340 KB |
Output is correct |
5 |
Correct |
1 ms |
340 KB |
Output is correct |
6 |
Correct |
5 ms |
3640 KB |
Output is correct |
7 |
Correct |
25 ms |
18688 KB |
Output is correct |
8 |
Correct |
72 ms |
55232 KB |
Output is correct |
9 |
Correct |
1 ms |
340 KB |
Output is correct |
10 |
Correct |
2 ms |
1108 KB |
Output is correct |
11 |
Correct |
3 ms |
1876 KB |
Output is correct |
12 |
Correct |
6 ms |
4896 KB |
Output is correct |
13 |
Correct |
5 ms |
3084 KB |
Output is correct |
14 |
Correct |
75 ms |
55236 KB |
Output is correct |
15 |
Correct |
1 ms |
468 KB |
Output is correct |
16 |
Correct |
51 ms |
22020 KB |
Output is correct |