Codeforces C. Palindromic Paths (迴文串 / 思維) (Round 89 Rated for Div.2)

傳送門

題意: 有一個由0和1組成的n * m矩陣,試問最少改變多少個數,可以使從(1,1)到(n,m)的所有路徑都是迴文串,輸出最小改變的數量。
在這裏插入圖片描述
思路:

  • 若要讓所有路徑爲迴文串,即以(1,1)爲圓心k爲半徑的環和以(n,m)爲圓心k爲半徑的環一樣。
  • 若每次都遍歷斜線會非常複雜。根據座標(x,y)來統計,因爲走到(x,y)需要x + y - 1步。便可以x + y - 爲第一關鍵字,a[x][y]的值爲第二關鍵字來把環上的數統計成{0}和{1}的集合。
  • 最後再遍歷去最小的集合計入ans就好。

代碼實現:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;

int t, n, m, ans;
int a[50][50], f[500][50];

signed main()
{
    IOS;

    cin >> t;
    while(t --){
        cin >> n >> m;
        me(f);
        for(int i = 1; i <= n; i ++){
            for(int j = 1; j <= m; j ++){
                cin >> a[i][j];
                f[i + j - 1][a[i][j]] ++;
            }
        }
        ans = 0;
        for(int i = 1, j = n + m - 1; j > i; i ++, j --)
            ans += min(f[i][0] + f[j][0], f[i][1] + f[j][1]);
        cout << ans << endl;
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章