#include<bits/stdc++.h>
#define IOS ios_base::sync_with_stdio(false);cin.tie();cout.tie();
#define all(x) x.begin(), x.end()
#define int long long
#define pq priority_queue
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define pp pop_back
#define F first
#define S second
using namespace std;
int ans = 100500;
int a[5][5];
int cx = 0;
int R, C;
void shift_r(int r, int v){
int b[5];
for (int i = 0; i < C; i++) b[i] = a[r][(i + v) % C];
for (int i = 0; i < C; i++) a[r][i] = b[i];
}
void shift_c(int c, int v){
int b[5];
for (int i = 0; i < R; i++) b[i] = a[(i + v) % R][c];
for (int i = 0; i < R; i++) a[i][c] = b[i];
}
int diff(int x, int y, int C) {return min(C - abs(x - y), abs(x - y));}
void find() {
bool check = 1;
for (int i = 0; i < R; i++)
for (int j = 1; j < C; j++)
check &= (a[i][j] == a[i][0]);
if (check) ans = min(ans, cx);
int b[5];
for (int i = 0; i < C; i++) b[i] = a[0][i];
map<int, int> M[5];
for (int i = 0; i < R; i++) {
bool r_eq = 0;
for (int tr = 0; tr < C; tr++) {
bool eq = 1;
for (int j = 0; j < C; j++) eq &= b[j] == a[i][j];
r_eq |= eq;
if (eq) M[i][tr]++;
shift_r(i, 1);
}
if (!r_eq) return;
}
for (int i = 0; i < C; i++) {
int c = i, cost = 0;
for (int j = 0; j < R; j++) {
int mnc = 10;
for (auto k : M[j]) mnc = min(mnc, diff(c, k.F, C));
cost += mnc;
}
ans = min(ans, cost + cx);
}
}
void calc(int x) {
if (x == C) {find(); return ;}
for (int i = 0; i < R; i++) {
cx += min(i, R - i);
calc(x + 1);
shift_c(x, 1);
cx -= min(i, R - i);
}
}
void solve () {
cin >> R >> C;
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
cin >> a[i][j];
calc(0);
cout << ans << endl;
}
signed main() {IOS solve(); return 0;}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
336 KB |
Output is correct |
2 |
Correct |
1 ms |
336 KB |
Output is correct |
3 |
Correct |
1 ms |
336 KB |
Output is correct |
4 |
Correct |
2 ms |
336 KB |
Output is correct |
5 |
Correct |
1 ms |
336 KB |
Output is correct |
6 |
Correct |
1 ms |
336 KB |
Output is correct |
7 |
Correct |
1 ms |
336 KB |
Output is correct |
8 |
Correct |
1 ms |
336 KB |
Output is correct |
9 |
Correct |
1 ms |
456 KB |
Output is correct |
10 |
Correct |
1 ms |
336 KB |
Output is correct |
11 |
Correct |
1 ms |
336 KB |
Output is correct |
12 |
Correct |
1 ms |
336 KB |
Output is correct |
13 |
Correct |
1 ms |
336 KB |
Output is correct |
14 |
Correct |
1 ms |
460 KB |
Output is correct |
15 |
Correct |
2 ms |
336 KB |
Output is correct |
16 |
Correct |
2 ms |
336 KB |
Output is correct |
17 |
Correct |
2 ms |
336 KB |
Output is correct |
18 |
Correct |
2 ms |
336 KB |
Output is correct |
19 |
Correct |
2 ms |
336 KB |
Output is correct |
20 |
Correct |
1 ms |
336 KB |
Output is correct |