首页 > 试题广场 >

翻之

[编程题]翻之
  • 热度指数:3617 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 1024M,其他语言2048M
  • 算法知识视频讲解
\hspace{15pt}对于给定的 nm 列的矩阵,每一个元素要么是 \texttt{`0'},要么是 \texttt{`1'}
\hspace{15pt}每一轮,你可以进行一次以下操作:
\hspace{23pt}\bullet\,选择一行的元素,将其全部反置,即 \texttt{`0'} 变为 \texttt{`1'}\texttt{`1'} 变为 \texttt{`0'}
\hspace{15pt}请你帮助小歪判断,若能进行任意多轮操作(也可以不进行操作),至多能使得多少列的元素均为 \texttt{`1'}。你只需要输出这个最大值。

输入描述:
\hspace{15pt}第一行输入两个正整数 n,m\left(1\leqq n,m\leqq 3 \times 10^3\right) 代表矩阵的行数和列数。
\hspace{15pt}此后 n 行,每行输入一个长度为 m 、仅由 \texttt{`0'}\texttt{`1'} 构成的字符串,代表矩阵每一行中的元素。


输出描述:
\hspace{15pt}输出一个整数,表示至多能使得多少列的元素均为 \texttt{`1'}
示例1

输入

3 4
1111
1111
1111

输出

4

说明

\hspace{15pt}在这个样例中,不需要进行操作,所有列的元素均为 \texttt{`1'}
示例2

输入

3 2
01
10
11

输出

1

说明

\hspace{15pt}在这个样例中,我们可以选择对第一行进行操作,使得第一行变为 \texttt{,此时,第一列的元素均为 \texttt{`1'}
把矩阵保存到数组里,遍历数组的每一列,若列字符串相等,说明无论翻转哪几行,这两个字符串始终都是相同的(能把它翻转为全为1),记录相等列字符串的最大值即为所求。
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
            int rows = in.nextInt();
            int cols = in.nextInt();
            in.nextLine();
            int res = 0;
            String[] row = new String[rows];
            for (int i = 0; i < rows; i++){
                row[i] = in.nextLine();
            }
            HashMap<String, Integer> map = new HashMap<>();
            for (int j = 0; j < cols; j++){
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < rows; i++){
                    sb.append(row[i].charAt(j));
                }
                String s = sb.toString();
                map.merge(s, 1, Integer :: sum);
                res = Math.max(res, map.get(s));
            }
           
            System.out.println(res);
        }
}

发表于 2025-07-21 17:00:33 回复(0)
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
//通过分析可知 本题变为 按照每一列的初始值 这样的列去统计次数 次数最多的值就是列全为1的值

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        in.nextLine();
        String[] row = new String[n];
        for (int i = 0; i < n; i++) {
                row[i] = in.nextLine();
            }
        //x为原数据数组 是按行排列的 现在改为按列排列
        Map<String,Integerz = new HashMap<>();
        for(int j = 0;j<m;j++){
            StringBuilder y = new StringBuilder();//每个列处理出来 然后记录哈希比较
            for(int i = 0;i<n;i++){
                y.append(row[i].charAt(j));
            }
            //这里 得到一列就添加进hashmap中一列处理掉
            String key = y.toString();
            z.put(key,z.getOrDefault(key,0)+1);
        }
        int count = 0;
        for(int k:z.values()){
            count = Math.max(count,k);
        }
        System.out.println(count);
    }
}
发表于 2025-03-16 13:16:58 回复(1)