Codeforces Round #647 (Div. 2) E. Johnny and Grandmaster

题目链接

E. Johnny and Grandmaster

题意:

给你一个长度为 n 的数组 K 和 一个整数 P, 让你将数组 K 分为A 、B两个集合

使得 ∑ P^KA - ∑ P^KB  的绝对值尽可能的小  

思路解法来自:博客

很妙的思路,思维很强

双模数就保证了,只有当两个模数下都是0 就保证了ans真正为0 

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
const int MOD = 1e9 + 7 , mod = 999998639;
int k[N] , n , p;
int pow_mod(int x , int n , int mod)
{
    int res = 1;
    while(n)
    {
        if(n & 1) res = res * x % mod;
        x = x * x % mod;
        n >>= 1;
    }
    return res;
}
signed main()
{
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while(t --)
    {
        cin >> n >> p;
        for(int i = 1 ; i <= n ; i ++) cin >> k[i];
        sort(k + 1 , k + 1 + n , greater<int>());
        int ans1 = 0 , ans2 = 0;
        for(int i = 1 ; i <= n ; i ++)
        {
            if(!ans1 && !ans2) 
                ans1 += pow_mod(p , k[i] , MOD), 
                ans2 += pow_mod(p , k[i] , mod);
            else
                ans1 = (ans1 - pow_mod(p , k[i] , MOD) + MOD) % MOD,
                ans2 = (ans2 - pow_mod(p , k[i] , mod) + mod) % mod;
        }
        cout << ans1 << '\n';
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41286356/article/details/106628409