n × n 網格,每格 0(髒)或 1(乾淨)。n ≤ 100,輸出最大全 1 行數。觀察發現:任意兩行若初始狀態完全相同,則無論如何翻轉列,它們始終保持相同(因為列操作對所有行同等作用)。
反之,若最終某些行變為全 1,則它們在初始時刻必須逐列相同。
因此,問題轉化為:找出現頻率最高的行模式(字符串),其頻率即為答案。
n 及 n 行字符串。#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) return 0;
unordered_map cnt;
string row;
int ans = 0;
for (int i = 0; i < n; ++i) {
cin >> row;
ans = max(ans, ++cnt[row]);
}
cout << ans << '\n';
return 0;
}
#include <stdio.h>
#include <string.h>
char a[102][102];
int main() {
int n, i, j, maxCnt = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++) scanf("%s", a[i]);
for (i = 1; i <= n; i++) {
int c = 0;
for (j = 1; j <= n; j++)
if (strcmp(a[i], a[j]) == 0) c++;
if (c > maxCnt) maxCnt = c;
}
printf("%d\n", maxCnt);
return 0;
}
複雜度:O(n² * L)(L=n),n=100 完全可接受。實際工程建議用哈希表降至 O(n * L)。
輸入: 4 0101 1000 1111 0101 行模式頻率: 0101 → 2 1000 → 1 1111 → 1 答案 = 2 ✓
掌握這類「反向思維:從目標狀態反推初始條件」,能化解大量看似無解的構造類問題。