美团算法面试题|2020-3-12

题目描述:小美曾经有一个特殊的数组, 这个数组的长度为n。但是她在打恐怖游戏的时候被吓得忘记了这个数组长什么样了。不过她还记得这个数组满足一些条件。首先这个数组的每个数的范围都在L和R之间。包括端点。除此之外,这个数组满足数组中的所有元素的和是k的倍数。但是这样的数组太多了,小美想知道有多少个这样的数组。你只需要告诉她在 模1e9+7意义下的答案就行了。

输入:
一行四个整数n,k,L,R
(1<=n<=1e5  1<=k<=10  1<=L<=R<=1e9)

输出:
输出一个数表示满足条件的数组的个数。

样例输入:
9 1 1 3

样例输出:
19683

 首先看到这道题,有点懵懵的,抓不到头绪,后来分析了一下样例,发现一个秘密。

[1-3]之间的数字,进行任意的排列组合长度为9,然后都是1的倍数,那不就是他们的排列组合,也就是 3的9次幂,赶紧用计算机算了一下,果然对了。然后推断,k的范围是1-10,那么也就是将上面的排列组合除k不就行了。

python脚本测试案例

n = 9
k = 1
L = 1
R = 3
res = (((R-L+1)**n)/k)%1000000007

 Java 版本

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n[] = new int[4];
        for(int i=0;i<n.length;i++) {
        	n[i] = scan.nextInt();
        }
        int pow = (int)Math.pow(n[3]-n[2]+1, n[0]);
        int res = pow/n[1] % 1000000007;
        System.out.println(res);
    }
}

写完以后我忽略了一个关键的问题,数据范围!!

于是代码改为:

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int sc[] = new int[4];
        for(int i=0;i<sc.length;i++) {
         sc[i] = scan.nextInt();
        }
        int n = sc[0];
        //BigInteger n = new BigInteger(sc[0]+"");
        BigInteger k = new BigInteger(sc[1]+"");
        BigInteger l = new BigInteger(sc[2]+"");
        BigInteger r = new BigInteger(sc[3]+"");
        //int pow = (int)Math.pow(n[3]-n[2]+1, n[0]);
        BigInteger addres = r.subtract(l).add(BigInteger.ONE);
        BigInteger pow = addres.pow(n);
        //int res = pow/n[1] % 1000000007;
        BigInteger res = pow.divide(k).remainder(new BigInteger("1000000007"));
        System.out.println(res);
    }
}
发布了80 篇原创文章 · 获赞 55 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/cong____cong/article/details/104830373