Meituan written test- Xiaomei’s element deletion

Xiaomei’s element deletion

Xiaomei has an array, and she wants to delete k elements so that the remaining elements are multiples of each other. Can you tell me how many deletion options there are?

Since the answer is too large, please model 10^9+7.

Enter description

In the first line, two integers n,k (1<=k<=n<=10^3) ​​are input, indicating the length of the array and the number of elements to be deleted.

The second line inputs n and k integers to represent the array a (1<=ai<=10^9).

It is guaranteed that there are no two equal elements in the given array.

Output description

Output an integer representing the answer.

Example 1

enter

6 4
1 4 2 3 6 7

output

8

illustrate

Option 1: Delete 1,4,2,7.

Option 2: Delete 1,4,3,7.

Option 3: Delete 1,3,6,7.

Option 4: Delete 4,2,3,6.

Option 5: Delete 4,2,3,7.

Option 6: Delete 4,2,6,7.

Option 7: Delete 4,3,6,7.

Option 8: Delete 2,3,6,7.

Ideas

We first sort all the numbers from small to large, and then record the index of the divisor of each number.

Then define the dp array: dp[i][j] = is the number of comparable numbers in the array ending with i and having length j.

We can get the state transition equation: dp[i][j] = sum of all dp[p][j-1] (p is a divisor of i)

Finally, we can accumulate dp[i][nk].

code

import java.util.*;

public class test {
    static final int MAXN = 1005;
    static final int MOD = 1000000007;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();

        int keep = n-k;

        int[] a = new int[MAXN];
        for(int i = 1 ;i<=n;i++){
            a[i] = scanner.nextInt();
        }

        Arrays.sort(a,1,n+1);
        List<Integer>[] yueshu = new ArrayList[MAXN];
        for(int i=1;i<=n;i++){
            yueshu[i] = new ArrayList<>();
        }

        for(int i=2;i<=n;i++){
            for(int j=1;j<i;j++){
                if(a[i]%a[j] == 0){
                    yueshu[i].add(j);
                }
            }
        }

//        定义dp[i][j] = 为以i为结尾的,长度为j的数组中可以相约的数的数量
        long[][] dp = new long[MAXN][MAXN];
        for(int i=1;i<=n;i++){
            dp[i][1] = 1;  //以i为结尾的,长度为1的数组中可以相约的数的数量为1
        }
        for(int i = 1;i<=n;i++){
            for (int j=2;j<=keep;j++){ // keep为需要保存的数字的个数
                for(int p : yueshu[i]){
                    dp[i][j] = dp[p][j-1] + dp[i][j];
                }
            }
        }

        int ans = 0;
        for (int i = 1;i<=n;i++){
            ans = (int) ((ans+dp[i][keep]) % MOD);
        }

        System.out.println(ans);
    }
}

Guess you like

Origin blog.csdn.net/qq_51118755/article/details/132966758