zoukankan      html  css  js  c++  java
  • LightOJ 1213(快速幂)

    Fantasy of a Summation

    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 ", ++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.

    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

    分析:代码中k个循环执行加法的所有次数为k*n^k次,由k个循环的对称性可知,

    数组中每个数被加的次数为k*n^(k-1)次,因此答案就是∑(a[i]*k*n^(k-1)),0<i<n,

    即sum*k*n^(k-1),然后用快速幂做。

    #include<cstdio>
    long long N,K,mod;
    long long pow(long long x,long long k)
    {
        long long res=1;
        while(k>0)
        {
            if(k&1) res=res*x%mod;
            k>>=1;
            x=x*x%mod;
        }
        return res;
    }
    int main()
    {
        int T,cas=0;
        scanf("%d",&T);
        while(T--)
        {
            long long sum=0,x;
            scanf("%lld%lld%lld",&N,&K,&mod);
            for(int i=0;i<N;i++)
            {
                scanf("%lld",&x);
                sum+=x;
            }
            sum%=mod;
            long long ans=pow(N,K-1);
            printf("Case %d: %lld
    ",++cas,ans%mod*K%mod*sum%mod);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    java保留字
    12个不可不知的Sublime Text应用技巧和诀窍
    人生准则
    基于Android 的蓝牙A2DP 功能的实现
    蓝牙协议栈详解
    我的2015计划
    今日学习
    滤波器介绍
    STLINK V2安装使用详解
    javascript闭包
  • 原文地址:https://www.cnblogs.com/ACRykl/p/8666909.html
Copyright © 2011-2022 走看看