UVA11718 Fantasy of a Summation【快速模幂】

If you think codes, eat codes then sometimes you may get stressed. In your dreams you may see huge codes, as I have seen once. Here is the code I saw in my dream.
在这里插入图片描述
Actually the code was about:
‘You are given 3 integers n, K, MOD and n integers A0, A1, A2, . . . , An−1. You have
to write K nested loops and calculate the summation of all Ai where i is the value of any nested loop variable.’

Now you have to find the result according to the code

Input
The first line of input contains T denoting the number of cases.
Each case starts with three integers — n (1 ≤ n ≤ 1000), K (1 ≤ K < 231), MOD (1 ≤ MOD ≤ 35000). The next line will contain n non-negative integers denoting A0, A1, A2, . . . , An−1. Each of these integers will be fit into a 32 bit signed integer.
Output
For each case print the case number and the result. Follow the sample output for the exact output format.
Sample Input
2
3 1 35000
1 2 3
2 3 35000
1 2
Sample Output
Case 1: 6
Case 2: 36

问题链接UVA11718 Fantasy of a Summation
问题简述:(略)
问题分析
     给程序代码,暂时不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA11718 Fantasy of a Summation */

#include <bits/stdc++.h>

using namespace std;

typedef long long ULL;

// 快速模幂计算函数
ULL powmod(ULL a, ULL n, ULL m)
{
    long long res = 1;
    while(n) {
        if(n & 1) {        // n % 2 == 1
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        n >>= 1;
    }
    return res;
}

int main()
{
    int t, caseno = 0;
    ULL n, k, mod, a, sum;
    scanf("%d", &t);
    while(t--) {
        scanf("%llu%llu%llu", &n, &k, &mod);
        sum = 0;
        for(int i = 0; i < n; i++) {
            scanf("%llu", &a);
            sum += a;
        }

        ULL tmp = powmod(n, k - 1, mod);
        printf("Case %d: %llu\n", ++caseno, tmp * (sum % mod) * (k % mod) % mod);
    }

    return 0;
}
发布了2126 篇原创文章 · 获赞 2306 · 访问量 254万+

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/104566246