LightOJ 1213 - Fantasy of a Summation (排列组合+快速幂)

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

If you think codes, eat codes then sometimes you may getstressed. In your dreams you may see huge codes, as I have seen once. Here isthe 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 calculatethe summation of all Ai where i is the value of anynested 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 integerswill 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次,但是每个数并不是加了n^k次,手写一下,用排列组合算下应该是n^(k-1)*k次,所以说ans=sum*n^(k-1)*k,,中间过程中取模就好了。


ac代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<set>
#include<queue>
#include<vector>
#define MAXN 1010000
#define LL long long
#define ll __int64
#include<iostream>
#include<algorithm>
#define INF 0xfffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1)
using namespace std;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL lcm(LL a,LL b){return a/gcd(a,b)*b;}
ll powmod(ll a,LL b,ll MOD){ll ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
//head
int main()
{
	int t;
	int cas=0;
	scanf("%d",&t);
	while(t--)
	{
		int n,k,mod;
		scanf("%d%d%d",&n,&k,&mod);
		ll ans=0;
		for(int i=0;i<n;i++)
		{
			int a;
			scanf("%d",&a);
			ans=(ans+a)%mod;
		}
		ll num=powmod(n,k-1,mod);
		printf("Case %d: ",++cas);
		printf("%d\n",(ans*num*k)%mod);
	}
	return 0;
}


你可能感兴趣的:(LightOJ 1213 - Fantasy of a Summation (排列组合+快速幂))