PDF (English) | Statistics | Forum |
Time Limit: 3 second(s) |
Memory Limit: 32 MB |
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 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 and106 denoting the array A as described above.
Each of the next q lines contains one query as described above.
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 |
Output for Sample Input |
1 3 5 1 2 3 1 0 0 3 1 0 2 1 1 |
Case 1: -4 0 4 |
题意就不说了,按照题目给的函数写,果断超时,于是想了一会发现sum+=a[i]*(n-1-i*2); 于是两层for循环改成了一次, 以为会过,又超时了。QAQ。。。 后来看队友的写法,当数组中值改变时,直接改sum的值,那样从头到尾只用了一次for循环求值。
当i=0时,有a0-a1+a0-a2+a0-a3+.....,当i=1时,有a1-a2+a1-a3+a1+.....,观察可得发现第一个式子刚好比第二个多出来 n-i 个(a0-a1)。之后操作时要改变值时直接在之前求得的总和身上改,例如改变了 a7 增加了2 则从第8到n 个数被 a7减时结果都要多2,而从第0个到第6个减 a7 时结果都小2 。
具体代码如下:
#include<cstdio> #include<cstring> #define maxn 100010 int a[maxn]; long long f(int a[],int n) { long long sum=0,temp=0; int i; for(i=1;i<n;++i) temp+=a[0]-a[i]; sum=temp; for(i=1;i<n;++i) { long long cnt=a[i]-a[i-1];//此处必须将a[i]-a[i-1]的结果转化为long long 型。 temp+=(n-i)*cnt; sum+=temp; } return sum; } int main() { int t,n,x,v,q,k=1,i,m; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&q); for(i=0;i<n;++i) scanf("%d",&a[i]); long long sum=f(a,n); printf("Case %d:\n",k++); while(q--) { scanf("%d",&m); if(m) printf("%lld\n",sum); else { scanf("%d%d",&x,&v); long long temp=v-a[x]; a[x]=v; sum+=(n-1-x-x)*temp; } } } return 0; }