Fantasy of a Summation
LightOJ - 1213If 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.
OutputFor each case, print the case number and result of the code.
Sample Input2
3 1 35000
1 2 3
2 3 35000
1 2
Sample OutputCase 1: 6
Case 2: 36
被执行了n^k次,而每次加k个数,所以总共下来一共会加k * n^k个数
同时我们还可以发现n个数中每一个数字被加的次数都是相同的,所以既然总共加了k * n^k个数,那么每个数字就加了
(k * n^k ) / n = k * n^(k-1) 次
所以总和 = a1 * k * n^(k-1) + a2 * k * n^(k-1) + …… +an * k * n^(k-1) =(a1+a2+……+an) * k * n^(k-1)
= sum * k * n^(k-1)
然后用快速幂求解即可
注意每一步都需要取模,求和sum的时候也要取模
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll q_pow(ll a,ll b,ll mod){
ll ans = 1;
while(b){
if(b & 1)
ans = ans * a % mod;
b >>= 1;
a = a * a % mod;
}
return ans % mod;
}
int main(){
int t,cas = 0;
scanf("%d",&t);
while(t--){
ll n,k,mod;
ll sum = 0;
cin >> n >> k >> mod;
for(ll i = 1; i <= n; i++){
ll x;
cin >> x;
sum = (sum + x) % mod;
}
ll ans = sum * k % mod;
ans = ans * q_pow(n,k-1,mod) % mod;
printf("Case %d: %d\n",++cas,ans);
}
return 0;
}
本文介绍了一种名为Fantasy of a Summation的算法问题,该问题涉及多重循环中的求和运算,并通过优化方法实现高效的计算。具体地,文章探讨了如何通过分析循环特性简化计算过程,使用快速幂算法来解决大规模数据的处理问题。
6947

被折叠的 条评论
为什么被折叠?



