贡献法:牛的基因学
牛的基因学
www.acwing.com/problem/content/5157/
距离计算(暴力): O ( n 3 ) O(n^{3}) O(n3)
for (int i = 0; i < n; i++) {
// s 向左移位 1 位
for (int j = 0; j < n; j++) {
// t 向左移位 1 位
for (int k = 0; k < n; k++) {
if (s[k] == t[k]) res++;
}
}
}
而且不仅是求距离,还需要构造这样的 t t t,可能的取值有 4 n 4^{n} 4n 种,必然会导致超时。
考虑优化:
- 距离计算
- 取值
贡献法:不是考虑组合,而是直接考虑单个字母的贡献
- 当保持 s s s 不变时,对 t t t 进行 n n n 次移位(一行),在这 n n n 次移位中,计算出 t t t 里面的每个字母各自在 s s s 中出现的次数,即能求出每个字母的贡献
- 且 t t t 的每个字母都是独立的 -> r e s = f 1 ( c ) + f 2 ( c ) + . . . + f n ( c ) res = f_1(c)+f_2(c)+...+f_n(c) res=f1(c)+f2(c)+...+fn(c),只需要让每一个 f i ( c ) f_i(c) fi(c) 取到最大,即每次取出现次数最多的字母
- 而后对于所有行,都是同理,取上一步得到的值 × n ×n ×n。这样就能得到距离最大的方案
- 出现次数最多的字母有 1 个: r e s = 1 n res=1^n res=1n;有 2 个: r e s = 2 n res=2^{n} res=2n;有 3 个: r e s = 3 n res=3^{n} res=3n…
import java.util.*;
public class Main {
static final int N = 100010, MOD = (int) 1e9 + 7;
static char[] str = new char[N];
static int n;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
str = sc.next().toCharArray();
// 统计出现次数最多的字母
Map<Character, Integer> count = new HashMap<>();
for (int i = 0; i < n; i++) {
if (count.containsKey(str[i])) {
count.put(str[i], count.get(str[i]) + 1);
} else {
count.put(str[i], 1);
}
}
int maxi = 0;
Set<Map.Entry<Character, Integer>> set = count.entrySet();
for (Map.Entry<Character, Integer> e : set) {
maxi = Math.max(e.getValue(), maxi);
}
int res = 0;
for (Map.Entry<Character, Integer> e : set) {
if (e.getValue() == maxi) {
res++;
}
}
System.out.println(qmi(res, n, MOD));
}
private static int qmi(int a, int k, int m) {
int res = 1;
while (k > 0) {
if (k % 2 == 1) {
res = (int) ((long) res * a % m);
}
a = (int) ((long) a * a % m);
k >>= 1;
}
return res;
}
}