1785 数据流中的算法
基准时间限制:1.5 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
收藏
关注
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
Wizmann (题目提供者)
题不难,数据坑…答案里平均数必须取整
每次用插入排序的方法 将用户满意度插入到链表里
用一个queue按顺序记录用户满意度的迭代器(删除时用)
O(n*k)
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
#include<queue>
#include<sstream>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
#define pll pair<ll,ll>
#define pid pair<int,double>
char CH;
int X;
inline int read() {
while (!isdigit(CH = getchar()));
X = CH - '0';
while (isdigit(CH = getchar())) {
X = X * 10 + CH - '0';
}
return X;
}
int main()
{
//freopen("C:\\Users\\Yang\\Desktop\\51nod_Problem_1785_Test_4_In.txt","r",stdin);
//freopen("C:\Users\Yang\Desktop\51nod_Problem_1785_Test_4_OutTmp.txt","w",stdout);
int n = read(), k = read(), oper;
list<int>ls;
deque<list<int>::const_iterator>que;
int sum = 0;
while (n--) {
oper = read();
if (oper == 1) {
int v = read();
sum += v;
if (que.size() == k) {
list<int>::const_iterator it = que.front();
que.pop_front();
sum -= *it;
ls.erase(it);
}
bool haveInsert = false;
for (list<int>::const_iterator it = ls.cbegin(); it != ls.cend(); ++it) {
if (*it >= v) {
que.push_back(ls.insert(it, v));
haveInsert = true;
break;
}
}
if (!haveInsert) {
ls.push_back(v);
list<int>::const_iterator it = ls.cend();
--it;
que.push_back(it);
}
}
if (oper == 2) {
printf("%.2f\n", (double)(sum/que.size()));
}
if (oper == 3) {
double aver = (double)sum / que.size();
double ans = 0;
for (list<int>::const_iterator it = ls.cbegin(); it != ls.cend(); ++it) {
ans += (aver - *it)*(aver - *it);
}
ans /= que.size();
printf("%.2f\n", ans);
}
if (oper == 4) {
double ans = 0;
int mid = que.size() / 2;
int i = 0;
for (list<int>::const_iterator it = ls.cbegin(); it != ls.cend(); ++it, ++i) {
if (i == mid - 1 && ls.size() % 2 == 0) {
ans += *it;
}
if (i == mid) {
ans += *it;
}
}
if (que.size() % 2 == 0) {
ans /= 2;
}
printf("%.2f\n", ans);
}
}
return 0;
}