LightOJ1213 Fantasy of a Summation

来源:互联网 发布:淘宝刷佣金单有风险吗 编辑:程序博客网 时间:2024/06/05 13:28

题目链接:点我


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 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.'

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

23 1 350001 2 32 3 350001 2

Sample Output

Case 1: 6Case 2: 36

题意:

求和

思路:

这里共进行了 nk加法,每次加法从中选取k个数,每个数被选到的概率为kn,所有答案为sumk1 * k;然后就可以直接用快速幂取模算就可以了.

代码:

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<iostream>using namespace std;typedef long long LL;LL qpow(LL x,LL n, LL mod){    LL ans = 1;    while(n){        if(n&1) ans =(ans * x) % mod;        x = (x *x) % mod;        n >>= 1;    }    return ans;}int main(){    LL n,k,mod;    int t,kase = 0;    scanf("%d", &t);    while( t--){        scanf("%lld %lld %lld",&n, &k,&mod);        LL sum = 0;        for(int i = 1; i <= n; ++i){            LL x;            scanf("%lld", &x);            sum += x;        }        sum %= mod;        printf("Case %d: %lld\n", ++kase,sum* k*qpow(n, k - 1, mod) % mod);    }    return 0;}
原创粉丝点击