数据流中的算法
Wizmann (命题人)
基准时间限制:1.5 秒 空间限制:131072 KB 分值: 20
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
解题思路:这道题在求中位数时,如果用排序的话,时间会超,所以采用了数组下标的方法。很巧妙
解题代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int n,k;
int ch[1000005];
int sh[105];
int tmp;
double sum,avg;
int read()
{
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;}
while(c>='0'&&c<='9')
{
x=x*10+c-'0';
c=getchar();
}
return x*f;
}
int main()
{
int a;
n=read();
k=read();
int cnt=0;
memset(sh,0,sizeof(sh));
sum=0;
for(int i=1;i<=n;i++)
{
a=read();
if(a==1)
{
ch[++cnt]=read();
if(cnt>k)
{
sum-=ch[cnt-k];
sh[ch[cnt-k]]--;
if(sh[ch[cnt-k]]<0)
sh[ch[cnt-k]]=0;
}
sum+=ch[cnt];
//printf("sum:%lf\n",sum);
sh[ch[cnt]]++;
tmp=(cnt>k?k:cnt);
}
else if(a==2)//求均值
{
avg=sum/tmp;
printf("%d.00\n",(int)avg);
}
else if(a==3)//求方差
{
avg=sum/tmp;
double ans=0;
for(int j=cnt;j>cnt-tmp;j--)
{
ans+=((ch[j]-avg)*(ch[j]-avg));
}
printf("%.2lf\n",ans/tmp);
}
else if(a==4)//求中位数
{
if(tmp%2)
{
int r=tmp/2+1;
int ans=0;
for(int j=0;j<=100;j++)
{
ans+=sh[j];
if(ans>=r)
{
printf("%.2lf\n",(double)j);
break;
}
}
}
else
{
int pos1=tmp/2,pos2=tmp/2+1;
int l=-1,r=-1;
int ans=0;
for(int j=0;j<=100;j++)
{
ans+=sh[j];
if(ans>=pos1&&l==-1)
l=j;
if(ans>=pos2&&r==-1)
r=j;
if(l!=-1&&r!=-1)
{
printf("%.2lf\n",(double)(l+r)*1.0/2);
break;
}
}
}
}
}
return 0;
}