贡献法:牛的基因学

贡献法:牛的基因学

牛的基因学

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 种,必然会导致超时。

考虑优化:

  1. 距离计算
  2. 取值

贡献法:不是考虑组合,而是直接考虑单个字母的贡献

  1. 当保持 s s s 不变时,对 t t t 进行 n n n 次移位(一行),在这 n n n 次移位中,计算出 t t t 里面的每个字母各自在 s s s 中出现的次数,即能求出每个字母的贡献
  2. 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) 取到最大,即每次取出现次数最多的字母
  3. 而后对于所有行,都是同理,取上一步得到的值 × n ×n ×n。这样就能得到距离最大的方案
  4. 出现次数最多的字母有 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值