[light oj 1328] A Gift from the Setter

1328 - A Gift from the Setter
 
Problem setting is somewhat of a cruel task of throwing something at the contestants and having them scratch their head to derive a solution. In this problem, the setter is a bit kind and has decided to gift the contestants an algorithm which they should code and submit. The C/C++ equivalent code of the algorithm is given below:
long long GetDiffSum( int a[], int n )
{
    long long sum = 0;
    int i, j;
    for( i = 0; i < n; i++ )
        for( j = i + 1; j < n; j++ )
            sum += abs( a[i] - a[j] ); // abs means absolute value
    return sum;
}

The values of array a[] are generated by the following recurrence relation:

a[i] = (K * a[i-1] + C) % 1000007 for i > 0

where KC and a[0] are predefined values. In this problem, given the values of K, C, n and a[0], you have find the result of the function

"long long GetDiffSum( int a[], int n )"

But the setter soon realizes that the straight forward implementation of the code is not efficient enough and may return the famous "TLE" and that's why he asks you to optimize the code.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case contains four integers K, C, n and a[0]. You can assume that (1 ≤ K, C, a[0] ≤ 104) and (2 ≤ n ≤ 105).

Output

For each case, print the case number and the value returned by the function as stated above.

Sample Input

Output for Sample Input

2

1 1 2 1

10 10 10 5

Case 1: 1

Case 2: 7136758

 

 
 
 
 
 
 
先根据递推式求出每一项,再nlogn求出两两只差绝对值的和。

nlogn求差的绝对值之和:
假设有5个数:a[1],a[2],a[3],a[4],a[5],则:
先排序、然后每次把每个数后面的数与其作差、
比如考虑a[1]时、则算出a[2]-a[1],a[3]-[1],a[4]-a[1],a[5]-a[1],
其中:a[3]-a[1]=a[3]-a[2]+a[2]-a[1]
a[4]-a[1]=a[4]-a[3]+a[3]-a[2]+a[2]-a[1]
a[5]-a[1]=a[5]-a[4]+a[4]-a[3]+a[3]-a[2]+a[2]-a[1]
这样显然可以直接得出:a[2]-a[1]算了4次,a[3]-a[2]算了3次,a[4]-a[3]算了2次,a[5]-a[4]算了1次。
然后再依次考虑a[2]时,                        a[3]-a[2]算了3次,a[4]-a[3]算了2次,a[5]-a[4]算了1次。
然后再依次考虑a[3]时,                                                 a[4]-a[3]算了2次,a[5]-a[4]算了1次。
然后再依次考虑a[4]时,                                                                          a[5]-a[4]算了1次。
统计一下:a[2]-a[1]算了1*4次,a[3]-a[2]算了2*3次,a[4]-a[3]算了3*2次,a[5]-a[4]算了4*1次。

综上、O(nlogn)排序,O(n)统计

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
#define INF 0x7fffffff
#define MOD 1000007
#define N 100010

ll sum;
ll a[N];
ll b[N];
ll k,c,n;

int main()
{
    ll T,i,j,iCase=1;
    scanf("%lld",&T);
    while(T--)
    {
        scanf("%lld%lld%lld%lld",&k,&c,&n,&a[0]);
        for(i=1;i<n;i++)
        {
            a[i]=(k*a[i-1]+c)%MOD;
        }
        sort(a,a+n);
        sum=0;
        for(i=1;i<n;i++)
        {
            sum+=(n-i)*i*(a[i]-a[i-1]);
        }
        printf("Case %lld: %lld\n",iCase++,sum);
    }
    return 0;
}

 

posted @ 2014-12-30 13:47  哈特13  阅读(328)  评论(0编辑  收藏  举报