LightOJ1213 Fantasy of a Summation —— 快速幂

题目链接:https://vjudge.net/problem/LightOJ-1213

1213 - Fantasy of a Summation
Time Limit: 2 second(s) Memory Limit: 32 MB

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.

#include <stdio.h>

int cases, caseno;
int n, K, MOD;
int A[1001];

int main() {
    scanf("%d", &cases);
    while( cases-- ) {
        scanf("%d %d %d", &n, &K, &MOD);

        int i, i1, i2, i3, ... , iK;

        for( i = 0; i < n; i++ ) scanf("%d", &A[i]);

        int res = 0;
        for( i1 = 0; i1 < n; i1++ ) {
            for( i2 = 0; i2 < n; i2++ ) {
                for( i3 = 0; i3 < n; i3++ ) {
                    ...
                    for( iK = 0; iK < n; iK++ ) {
                        res = ( res + A[i1] + A[i2] + ... + A[iK] ) % MOD;
                    }
                    ...
                }
            }
        }
        printf("Case %d: %d ", ++caseno, res);
    }
    return 0;
}

Actually the code was about: 'You are given three integers nKMOD 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.'

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case starts with three integers: n (1 ≤ n ≤ 1000), K (1 ≤ K < 231), MOD (1 ≤ MOD ≤ 35000). The next line contains 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 result of the code.

Sample Input

Output for Sample Input

2

3 1 35000

1 2 3

2 3 35000

1 2

Case 1: 6

Case 2: 36

 

题解:

根据代码, 可知每个数在特定位置中出现了 n^(k-1)次,而总共有k个位置,所以每个数出现了k*n^(k-1)次,所以答案为: ∑ a[i]*k*n^(k-1),1<=i<=n。

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <cmath>
 7 #include <queue>
 8 #include <stack>
 9 #include <map>
10 #include <string>
11 #include <set>
12 using namespace std;
13 typedef long long LL;
14 const int INF = 2e9;
15 const LL LNF = 9e18;
16 //const int MOD = 35000+7;
17 const int MAXN = 1e6+10;
18 
19 int MOD;
20 LL qpow(LL x, LL y)
21 {
22     LL s = 1;
23     while(y)
24     {
25         if(y&1) s = (s*x)%MOD;
26         x = (x*x)%MOD;
27         y >>= 1;
28     }
29     return s;
30 }
31 
32 int main()
33 {
34     int T, n, k, kase = 0;
35     scanf("%d", &T);
36     while(T--)
37     {
38         scanf("%d%d%d", &n,&k,&MOD);
39         LL sum = 0;
40         for(int i = 1; i<=n; i++)
41         {
42             LL val;
43             scanf("%lld", &val);
44             sum = (sum+(val%MOD))%MOD;
45         }
46 
47         LL ans = (((1LL*sum*k)%MOD)*qpow(n, k-1))%MOD;
48         printf("Case %d: %lld
", ++kase, ans);
49     }
50 }
View Code
原文地址:https://www.cnblogs.com/DOLFAMINGO/p/8377110.html