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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章