This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
//#define int long long
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define sc second
#define endl "\n"
#define pii pair<int,int>
using namespace std;
const int MAXN = 4005;
const int mod7 = 1e9+7;
const long long inf = 1e9;
struct str
{
int a,b,c;
};
struct cmp {
bool operator() (str a, str b) const {
return a.a < b.a;
}
};
vector<vector<int>> dist(MAXN, vector<int>(MAXN,inf));
set<str, cmp> pq;
signed main()
{
ios_base::sync_with_stdio(false),cin.tie(0), cout.tie(0);
int tt=1;
//cin >> tt;
while(tt--)
{
int n,m;
cin >> n >> m;
vector<string>mat(n);
for(int i=0; i<n; i++)cin >> mat[i];
dist[0][0] = 0;
pq.insert({0,0,0});
while(!pq.empty())
{
auto it = pq.begin();
int i = it->b;
int j = it->c;
pq.erase(it);
if(i>0 && mat[i-1][j]!='.')
{
int cost = (mat[i][j] != mat[i-1][j]);
if(dist[i-1][j] > dist[i][j] + cost)
{
pq.erase({dist[i-1][j], i-1, j});
dist[i-1][j] = dist[i][j] + cost;
pq.insert({dist[i-1][j], i-1, j});
}
}
if(i<n-1&& mat[i+1][j]!='.')
{
int cost = (mat[i][j] != mat[i+1][j]);
if(dist[i+1][j] > dist[i][j] + cost)
{
pq.erase({dist[i+1][j], i+1, j});
dist[i+1][j] = dist[i][j] + cost;
pq.insert({dist[i+1][j], i+1, j});
}
}
if(j>0&& mat[i][j-1]!='.')
{
int cost = (mat[i][j] != mat[i][j-1]);
if(dist[i][j-1] > dist[i][j] + cost)
{
pq.erase({dist[i][j-1], i, j-1});
dist[i][j-1] = dist[i][j] + cost;
pq.insert({dist[i][j-1], i, j-1});
}
}
if(j<m-1 && mat[i][j+1]!='.')
{
int cost = (mat[i][j] != mat[i][j+1]);
if(dist[i][j+1] > dist[i][j] + cost)
{
pq.erase({dist[i][j+1], i, j+1});
dist[i][j+1] = dist[i][j] + cost;
pq.insert({dist[i][j+1], i, j+1});
}
}
}
int mx = 0;
for(int i = 0;i<n; i++)
{
for(int j=0; j<m; j++)
{
if(dist[i][j]!=inf)mx = max(mx, dist[i][j]);
}
}
cout << mx+1 << endl;
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |