51 Nod 1785 数据流中的算法

                            1785 数据流中的算法
 
51nod近日上线了用户满意度检测工具,使用高级人工智能算法,通过用户访问时间、鼠标轨迹等特征计算用户对于网站的满意程度。
 
现有的统计工具只能统计某一个窗口中,用户的满意程度的均值。夹克老爷想让你为统计工具添加一个新feature,即在统计均值的同时,计算窗口中满意程度的标准差和中位数(均值需要向下取整)。
Input
第一行是整数n与k,代表有n次操作,时间窗口大小为k。 
(1 <= n <= 10^6, 1 <= k <= 100)

接下来的n行,每行代表一次操作。操作有“用户访问”、“查询均值”、“查询方差”、“查询中位数”四种。每行的第一个数代表操作类型。

操作数1:用户访问
输入格式:<1, v>
用户的满意度v为闭区间[0, 100]中的任意整数。用户每访问一次,数据更新,移动统计窗口。

操作数2:查询均值
输入格式:<2>
统计窗口内的用户满意度的均值。

操作数3:查询方差
输入格式:<3>
统计窗口内用户满意度的方差

操作数4:查询中位数
输入格式:<4>
统计窗口内用户满意度的中位数

p.s. 在有查询请求时,窗口保证不为空
p.s.s. 有查询请求时,窗口可能不满
Output
对于“查询均值”、“查询方差”、“查询中位数”操作的结果,输出保留两位小数。
Input示例
12 3
1 1
1 2
1 3
2
3
4
1 4
1 5
1 6
2
3
4
Output示例
2.00
0.67
2.00
5.00
0.67
5.00

可以线段树维护 但是暴力模拟也可以
均值和方差用个前缀和可以0(n)求解
中位数就直接暴力求解
PS:有个博客的题解 方差和中位数都是 暴力求解 1000ms+ 跑过
   结果 我却2700ms+ T掉了。 理论上我是要比那个人快的。。
   把语言换成 VC++ 可以1300ms卡掉

 1 #include <cctype>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 const int MAXN=1010;
 7 
 8 int n,k,tot,sum,t,sumx;
 9 
10 int A[MAXN],a[MAXN];
11 
12 inline void read(int&x) {
13     int f=1;register char c=getchar();
14     for(x=0;!isdigit(c);c=='-'&&(f=-1),c=getchar());
15     for(;isdigit(c);x=x*10+c-48,c=getchar());
16     x=x*f;
17 }
18 
19 int hh() {
20     read(n);read(k);
21     memset(a,-1,sizeof a);tot=1;
22     
23     for(register int flag,v,i=1; i<=n; ++i) {
24         read(flag);
25         if(flag==1) {
26             read(v);
27             int L=a[tot]>0?a[tot]:0;
28             sum+=v-L;
29             sumx+=v*v-L*L;
30             if(a[tot]==-1) ++t;
31             a[tot++]=v;
32             if(tot>k) tot=1;
33         }
34         else if(flag==2) {
35             int ans=sum/t;
36             printf("%.2lf
",ans*1.0);
37         }
38         else if(flag==3) {
39             double p,ans=.0;
40             p=sum*1.0/t;
41             ans=sumx-2*p*sum;
42             printf("%.2lf
",ans/t*1.0+p*p);
43         }
44         else {
45             int cnt=0;
46             for(register int j=1; j<=k; ++j) if(a[j]!=-1) A[++cnt]=a[j];
47             std::sort(A+1,A+1+cnt);
48             printf("%.2lf
",(A[(cnt+1)/2]+A[cnt/2+1])/2.0);
49         }
50     }
51     return 0;
52 }
53 
54 int sb=hh();
55 int main(int argc,char**argv) {;}
代码
 
原文地址:https://www.cnblogs.com/whistle13326/p/7719218.html