#include<bits/stdc++.h>
#define task "C"
#define ll long long
#define ld long double
#define fi first
#define se second
#define pb push_back
using namespace std;
const int MAXN = 2e3 + 5;
const ll INF = 1e18 + 5;
int m, n;
char c[MAXN][MAXN];
void Input()
{
cin >> m >> n;
for (int i = 1; i <= m; i++)
{
string s;
cin >> s;
for (int j = 0; j < n; j++)
c[i][j + 1] = s[j];
}
}
bool trace[MAXN][MAXN], ava[MAXN][MAXN], ava2[MAXN][MAXN];
pair<int, int> down(pair<int, int> u)
{
return {u.fi + 1, u.se};
}
pair<int, int> rght(pair<int, int> u)
{
return {u.fi, u.se + 1};
}
bool chk(pair<int, int> u)
{
return (u.fi >= 1 && u.se >= 1 && u.fi <= m && u.se <= n);
}
void Solve()
{
deque<pair<int, int>> Q;
Q.pb({1, 1});
ava[1][1] = 1;
while (true)
{
if (ava[m][n])
break;
vector<pair<int, int>> vc;
while (!Q.empty())
{
auto u = Q.front();
//cerr << u.fi << ' ' << u.se << '\n';
auto v = down(u);
if (chk(v) && !ava2[v.fi][v.se])
{
ava2[v.fi][v.se] = 1;
trace[v.fi][v.se] = 0;
vc.pb(v);
}
v = rght(u);
if (chk(v) && !ava2[v.fi][v.se])
{
ava2[v.fi][v.se] = 1;
trace[v.fi][v.se] = 1;
vc.pb(v);
}
Q.pop_front();
}
char minc = 'z';
for (auto p : vc)
minc = min(minc, c[p.fi][p.se]);
for (auto p : vc)
{
//cerr << p.fi << ' ' << p.se << '\n';
ava2[p.fi][p.se] = 0;
if (c[p.fi][p.se] == minc && !ava[p.fi][p.se])
{
Q.pb(p);
ava[p.fi][p.se] = 1;
}
}
}
vector<char> res;
pair<int, int> en = {m, n};
while (en != make_pair(1, 1))
{
res.pb(c[en.fi][en.se]);
if (trace[en.fi][en.se])
en.se--;
else
en.fi--;
}
res.pb(c[1][1]);
reverse(res.begin(), res.end());
for (char t : res)
cout << t;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
if (fopen(task".INP","r"))
{
freopen(task".INP","r",stdin);
//freopen(task".OUT","w",stdout);
}
Input();
Solve();
}
Compilation message
pohlepko.cpp: In function 'int main()':
pohlepko.cpp:110:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
110 | freopen(task".INP","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
340 KB |
Output is correct |
2 |
Correct |
2 ms |
4164 KB |
Output is correct |
3 |
Correct |
1 ms |
340 KB |
Output is correct |
4 |
Correct |
1 ms |
596 KB |
Output is correct |
5 |
Correct |
1 ms |
340 KB |
Output is correct |
6 |
Correct |
2 ms |
3284 KB |
Output is correct |
7 |
Correct |
9 ms |
12068 KB |
Output is correct |
8 |
Correct |
19 ms |
19912 KB |
Output is correct |
9 |
Correct |
1 ms |
1108 KB |
Output is correct |
10 |
Correct |
1 ms |
2004 KB |
Output is correct |
11 |
Correct |
1 ms |
1364 KB |
Output is correct |
12 |
Correct |
5 ms |
8532 KB |
Output is correct |
13 |
Correct |
9 ms |
16212 KB |
Output is correct |
14 |
Correct |
18 ms |
19872 KB |
Output is correct |
15 |
Correct |
1 ms |
1108 KB |
Output is correct |
16 |
Correct |
27 ms |
13688 KB |
Output is correct |