light oj 1220 Fantasy of a Summation

来源:互联网 发布:linux nas挂载 编辑:程序博客网 时间:2024/06/05 16:04

Fantasy of a Summation

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


题意:给一个公式,想出优化方案

根据公式可以看出每个数循环了n^k次,没次有k个数相加,所以一共有k*n^k个数相加,可以知道每个数加的次数一定相等,所以实际上每个数相加的次数为k/n*n^k即k*n^(k-1)次,所以sum*k*n^(k-1)即为答案


#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<string>#include<queue>#include<deque>#include<algorithm>#include<set>#include<map>#include<stack>#include<utility>using namespace std;typedef long long ll;#define for1(i,a) for(int (i)=1;(i)<=(a);(i)++)#define for0(i,a) for(int (i)=0;(i)<(a);(i)++)#define pf printf#define sf scanf#define mem(i,a) memset(i,a,sizeof i)#define eps 1e-10#define pi acos(-1.0)#define _s second#define _f firstint T,n,mod,a[1010];ll k,ans;int quick()//快速幂{    ll m=k-1,b=1;    while(m)    {        if(m&1)b=b*n%mod;        n=n*n%mod;        m>>=1;    }    return ans*b%mod;}int main(){    sf("%d",&T);    for1(i,T)    {        ans=0;        sf("%d%lld%d",&n,&k,&mod);        for1(i,n)            sf("%d",&a[i]),ans+=a[i];        ans=quick();        pf("Case %d: %lld\n",i,ans*k%mod);    }    return 0;}