Light OJ 1213 Fantasy of a Summation (快速幂+规律)

本文描述了一个关于在梦中见到的复杂代码的问题,该代码涉及计算特定数组在多个嵌套循环下的所有元素组合之和,并提供了两种解决方案。输入包括多组测试用例,每组包含整数n、K及MOD,随后是一系列整数。
E - Fantasy of a Summation
Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu
Appoint description: 

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

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define LL long long
using namespace std;
LL mod(LL a,LL b,LL c)
{
    LL res=1%c;
	LL t=a%c;
	while(b)
	{
		if(b%2)
		{
			res=res*t%c;
		}
		t=t*t%c;
		b=b/2;
	 } 
	 return res;
}
int main()
{
	LL n,k,t,m,i,j,a;
	scanf("%lld",&t);
	LL l=1;
	while(t--)
	{
		scanf("%lld%lld%lld",&n,&k,&m);
		LL sum=0;
		for(i=0;i<n;i++)
		{
			scanf("%lld",&a);
			sum+=a;
			sum=sum%m;
		}
		LL ans=((sum*mod(n,k-1,m))%m)*k%m;
		printf("Case %lld: %lld\n",l++,ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值