light oj 1213

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

题意:告诉你这段代码,然后优化,求res; n (1 ≤ n ≤ 1000), K (1 ≤ K < 231), MOD (1 ≤ MOD ≤ 35000)

我们很容易就知道最内成的加法式子执行了n^K次,每次加了K个数,所以一共加了K*n^K个数,一共有n个数,每个数加的次数一定是相同的,所以每个数都加了K*n^(K-1)次,所以结果就是Sum*K*n^(K-1)%mod; 快速幂求一下即可;

代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll mod;
ll qpow(ll a,ll b)
{
	ll base=a,ans=1;
	while(b)
	{
		if(b&1)
		{
			ans=(ans*base)%mod;
		}
		base=(base*base)%mod;
		b>>=1;
	}
	return ans%mod;
}
int main()
{
	int t;
	scanf("%d",&t);
	int cas=1;
	while(t--)
    {
        ll n,k;
        scanf("%lld%lld%lld",&n,&k,&mod);
        ll x;
        ll sum=0;
        for(ll i=1;i<=n;i++)
        {
            scanf("%lld",&x);
            sum=(sum+x)%mod;
        }
        sum%=mod;
        ll tot=sum*k* qpow(n,k-1)%mod;
        printf("Case %d: %lld\n",cas++,tot);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/88697348