Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- -------------- | /
- | | /
- | | /
- | * |/ | | ------ *
- | | | | / \
- | | |\ | | | |\ |
- \ | | | \ | | | | \ |
- \ | | | \ | | \ / \ |
- V | | \ \__/| ----- \ |
- */
- #include <bits/stdc++.h>
- using namespace std;
- #define EmiliaMyWife ios::sync_with_stdio(0); cin.tie(NULL);
- #define endl '\n'
- #define mem(i,j) memset(i,j,sizeof i);
- #define F first
- #define S second
- #define pb push_back
- #define mp make_pair
- #define all(a) a.begin(), a.end()
- #define bit(s,i) (((s)>>(i))&1LL)
- #define lowbit(x) (x&-x)
- #define siz(v) (long long)v.size()
- typedef int64_t ll;
- typedef uint64_t ull;
- typedef pair<int,int> pii;
- typedef pair<ll, ll> pll;
- const double EPS = 1e-8;
- const int INF = 0x3F3F3F3F;
- const ll LINF = 4611686018427387903;
- const int MOD = 1e9+7;
- const int MAXN = 2e5+9;
- /*-----------------------------------------------------------------------------------------------------*/
- signed main() {
- EmiliaMyWife
- int n, m;
- cin >> n >> m;
- vector<vector<int>> arr(n, vector<int>(m));
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> arr[i][j];
- }
- }
- vector<vector<int>> cnt(n*m+1);
- for(int j = 0; j < m; j++) {
- for(int i = 0; i < n; i++) {
- if(((arr[i][j]%m)==(j+1)) && (arr[i][j]<=n*m)) cnt[arr[i][j]].pb(i);
- }
- }
- vector<int> ccnt(n*m+1);
- for(int i = 1; i <= n*m; i++) {
- if(cnt[i].empty()) ccnt[i]=INF;
- else {
- // 沒有要再用cnt了所以可以改掉,如要再用的話可以複製一份改值
- for(int &x: cnt[i]) x = min(abs(x-(i-1)/m), n-abs((i-1)/m-x));
- ccnt[i] = *min_element(all(cnt[i]));
- }
- }
- int ans=0;
- for(int j = 0; j < m; j++) {
- int opp = INF;
- for(int i = 0; i < n; i++) {
- int x = ccnt[i*m+j+1];
- if(abs(opp) > n-abs(i-x)) opp = n - abs(x - i);
- if(abs(opp) > abs(i-x)) opp = i - x;
- }
- if(opp==INF) opp=0;
- int cnt1=n, cnt2=n;
- opp %= n;
- for(int i = 0; i < n; i++) {
- if(arr[(ccnt[i*m+j+1]+opp )%n][j]==(i*m+j+1)) cnt1--;
- if(arr[(ccnt[i*m+j+1]-opp+n)%n][j]==(i*m+j+1)) cnt2--;
- }
- ans += min(cnt1, cnt2);
- if(opp) ans++;
- }
- cout << ans;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment