Time Limit:3000MS Memory Limit:32768KB 64bit IO
Format:%lld & %llu(明确指出64位格式为lld,用I64d会wa!!!)
Description
The problem you need to solve here is pretty simple. You are give a function f(A, n), where A is an array of integers and n is the number of elements in the array. f(A, n) is defined as follows:
long long f( int A[], int n ) { // n = size of A
long long sum = 0;
for( int i = 0; i < n; i++ )
for( int j = i + 1; j < n; j++ )
sum += A[i] - A[j];
return sum;
}
Given the array A and an integer n, and some queries of the form:
1) 0 x v (0 ≤ x < n, 0 ≤ v ≤ 106), meaning that you have to change the value of A[x] to v.
2) 1, meaning that you have to find f as described above.
Input
Input starts with an integer T (≤ 5), denoting the number of test cases.
Each case starts with a line containing two integers: n and q (1 ≤ n, q ≤ 105). The next line contains n space separated integers between 0 and 106 denoting the array A as described above.
Each of the next q lines contains one query as described above.
Output
For each case, print the case number in a single line first. Then for each query-type "1" print one single line containing the value of f(A, n).
Sample Input
1
3 5
1 2 3
1
0 0 3
1
0 2 1
1
Sample Output
Case 1:
-4
0
4
这道题吧,其实水水就过去了,刚开始以为要用线段树来做,后来发现了个求和规律= =,也就是,假设有n个数,那么根据上面的代码求出的sum方法,可推出一个求和规律,由于下标是从0开始,所以先将n减一,然后可得求和规律即sum=(n)*a[0]+(n-2)*a[1]+(n-4)*a[2]+(n-6)*a[3]+(n-8)*a[4]+……(n-2*n)*a[n-1];也就是说,他的和等于系数从n-1开始每次减2,乘上a[i];(不理解的可以验证几组数据很容易就发现了),求和公式得出来了,那么如果进行更新时候,只需要将要更新的一项去掉,然后加上该项更新后的值就行了,如果进行询问,直接输出sum;
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define N 50010
#define INF 999999999
using namespace std;
int a[100010],b[100010];
int main()
{
int n,p,q,i,x,v,h;
long long sum;//注意用long long不然会溢出;
int t;
int k=0;
scanf("%d",&t);
while(t--)
{
sum=0;
scanf("%d%d",&n,&q);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
h=n;
n--;
for(i=0; i<h; i++)
{
sum+=((long long)n)*a[i];//进行求和运算;
b[i]=n;把每一项对应的系数存起来,方便后面的更新;
n=n-2;
}
printf("Case %d:\n",++k);
while(q--)
{
scanf("%d",&p);
if(p==0)
{
scanf("%d%d",&x,&v);
sum-=((long long)b[x])*a[x];//如果要把a[x]的值更新为v,那么先将这一项与对应系数的乘积减去;
sum+=((long long)b[x])*v;//然后再加上更新后的值与对应系数的乘积;
a[x]=v;//这里很重要,注意把a[x]更新为v
}
if(p==1)
printf("%lld\n",sum);//输出用lld,lld,不能用I64d,因为题目上明确说了64位输出格式为lld,我只想说没看见题目前面的要求,用I64wa了N次= =
}
}
return 0;
}