Q老師與十字叉

問題描述

Q老師 得到一張 n 行 m 列的網格圖,上面每一個格子要麼是白色的要麼是黑色的。

Q老師認爲失去了 十字叉 的網格圖莫得靈魂. 一個十字叉可以用一個數對 x 和 y 來表示, 其中 1 ≤ x ≤ n 並且 1 ≤ y ≤ m, 滿足在第 x 行中的所有格子以及在第 y 列的 所有格子都是黑色的

例如下面這5個網格圖裏都包含十字叉
在這裏插入圖片描述
第四個圖有四個十字叉,分別在 (1, 3), (1, 5), (3, 3) 和 (3, 5).

下面的圖裏沒有十字叉
在這裏插入圖片描述
Q老師 得到了一桶黑顏料,他想爲這個網格圖注入靈魂。 Q老師 每分鐘可以選擇一個白色的格子並且把它塗黑。現在他想知道要完成這個工作,最少需要幾分鐘?

Input

第一行包含一個整數 q (1 ≤ q ≤ 5 * 10^4) — 表示測試組數

對於每組數據:
第一行有兩個整數 n 和 m (1 ≤ n, m ≤ 5 * 10^4, n * m ≤ 4 * 10^5) — 表示網格圖的行數和列數

接下來的 n 行中每一行包含 m 個字符 — ‘.’ 表示這個格子是白色的, ‘*’ 表示這個格子是黑色的

保證 q 組數據中 n 的總和不超過 5 * 10^4, n*m 的總和不超過 4 * 10^5

Output

答案輸出 q 行, 第 i 行包含一個整數 — 表示第 i 組數據的答案

Sample input

9
5 5
..*..
..*..
*****
..*..
..*..
3 4
****
.*..
.*..
4 3
***
*..
*..
*..
5 5
*****
*.*.*
*****
..*.*
..***
1 4
****
5 5
.....
..*..
.***.
..*..
.....
5 3
...
.*.
.*.
***
.*.
3 3
.*.
*.*
.*.
4 4
*.**
....
*.**
*.**

Sample output

0
0
0
0
0
4
1
1
2

解題思路

可以先橫向搜索矩陣,將所有點存儲當前行內 ’ . ’ 的數量,然後再縱向搜索,加上之前的數量,這樣可以把時間複雜度控制在O(n2)O(n^2)。如果當前點是 ’ . ’ ,那麼數量減一(因爲算了兩次)。如果每個點都重新搜索橫向和縱向,會達到O(n3)O(n^3),導致TLETLE

完整代碼

//#pragma GCC optimize(2)
//#pragma G++ optimize(2)
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

int q,n,m,ans;
int getint(){
    int x=0,s=1; char ch=' ';
    while(ch<'0' || ch>'9'){ ch=getchar(); if(ch=='-') s=-1;}
    while(ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar();}
    return x*s;
}
int main(){
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    scanf("%d",&q);
    while(q--){
        scanf("%d %d",&n,&m);
        char ch[n+10][m+10];
        int a[n+10][m+10];
        memset(ch,0,sizeof(ch));
        memset(a,0,sizeof(a));
        ans=INT_MAX/2;
        for (int i=1; i<=n; i++)
            for (int j=1; j<=m; j++)
                scanf(" %c",&ch[i][j]);

        for (int i=1; i<=n; i++){
            int temp=0;
            for (int j=1; j<=m; j++){
                if(ch[i][j]=='.') temp++;
            }
            for (int j=1; j<=m; j++){
                a[i][j]=temp;
            }
        }
        for (int j=1; j<=m; j++){
            int temp=0;
            for (int i=1; i<=n; i++){
                if(ch[i][j]=='.') temp++;
            }
            for (int i=1; i<=n; i++){
                a[i][j]+=temp;
                if(ch[i][j]=='.') a[i][j]--;
            }
        }
        for (int i=1; i<=n; i++){
            for (int j=1; j<=m; j++){
                ans=min(ans,a[i][j]);
            }
        }
        printf("%d\n",ans);
    }

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