LightOJ 1213 Fantasy of a Summation(规律 + 快数幂)

http://lightoj.com/volume_showproblem.php?problem=1213

 Fantasy of a Summation
Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu

Description

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\n", ++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

2

3 1 35000

1 2 3

2 3 35000

1 2

Sample Output

Case 1: 6

Case 2: 36

 
根据题目上所附的代码不难看出题意,不再多说
公式   (sum*n^(k - 1) * k) % mod
好不容易推出公式,结果才取余上一直出错,郁闷半天!!!!
 
n^(k - 1)要用快数幂来求解
为了防止溢出就尽情地去取余吧。。。
 
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>

using namespace std;

const int N = 1010;
const int INF = 0x3f3f3f3f;
typedef long long ll;

int mod;

ll Pow(int a, int b, int c)
{
   ll ans = 1;
   a %= c;
   while(b)
   {
       if(b % 2 == 1)
        ans = (ans * a) % c;
       a = (a * a) % c;
       b /= 2;
   }
    return ans;
}

int main()
{
    int t, a[N], p = 0;;
    int n, k;
    ll sum;
    scanf("%d", &t);
    while(t--)
    {
        p++;
        sum = 0;
        scanf("%d%d%d", &n, &k, &mod);
        for(int i = 0 ; i < n ; i++)
        {
            scanf("%d", &a[i]);
             sum += a[i];
        }
        ll s;
        s = Pow(n, k - 1, mod);
        s *= k;
        sum %= mod;
        sum *= s;
        sum %= mod;
        printf("Case %d: %lld\n", p, sum);
    }
    return 0;
}
/*
3
2 4 3
1 30
4 9 5
22 18 2 22
2 2147483647 3333
2147483647 2147483647
*/

 

 
posted @ 2015-11-06 15:06  午夜阳光~  阅读(368)  评论(0编辑  收藏  举报