首页 > 代码库 > [CF808B] Average Sleep Time([强行]树状数组,数学)

[CF808B] Average Sleep Time([强行]树状数组,数学)

题目链接:http://codeforces.com/contest/808/problem/B

题意:n个数,求其中每k个数的和的平均值。

鬼知道我怎么会石乐志上来就用了树状数组。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long LL;
 5 const int maxn = 200200;
 6 int n, k;
 7 LL a[maxn], bit[maxn];
 8 int lowbit(int x) {return x&(-x);}
 9 void add(int id,LL val) {for(int i=id;i<=k;i+=lowbit(i))bit[i]+=val;}
10 void sum(int id, LL& ret) {for(int i=id;i>0;i-=lowbit(i))ret+=bit[i];}
11 
12 int main() {
13     // freopen("in", "r", stdin);
14     while(~scanf("%d%d",&n,&k)) {
15         LL ret = 0;
16         memset(bit, 0, sizeof(bit));
17         for(int i = 1; i <= n; i++) scanf("%I64d", &a[i]);
18         for(int i = 1; i <= k; i++) add(i,a[i]);
19         sum(k, ret);
20         for(int i = k + 1; i <= n; i++) {
21             add(i%k+1,-a[i-k]);
22             add(i%k+1,a[i]);
23             sum(k, ret);
24         }
25         printf("%.10f\n", (double)ret/(n-k+1));
26     }
27     return 0;
28 }

 

直接用前缀和维护搞。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long LL;
 5 const int maxn = 200200;
 6 int n, k;
 7 LL a[maxn], s[maxn];
 8 
 9 int main() {
10     // freopen("in", "r", stdin);
11     while(~scanf("%d%d",&n,&k)) {
12         memset(s, 0, sizeof(s));
13         for(int i = 1; i <= n; i++) {
14             scanf("%I64d", &a[i]);
15             s[i] = s[i-1] + a[i];
16         }
17         LL ret = .0;
18         for(int i = k; i <= n; i++) ret += s[i] - s[i-k];
19         printf("%.10f\n", (double)ret / (n - k + 1));
20     }
21     return 0;
22 }

 

[CF808B] Average Sleep Time([强行]树状数组,数学)