HDU 2993 MAX Average Problem(斜率优化)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2993

Problem Description
Consider a simple sequence which only contains positive integers as a1, a2 ... an, and a number k. Define ave(i,j) as the average value of the sub sequence ai ... aj, i<=j. Let’s calculate max(ave(i,j)), 1<=i<=j-k+1<=n.
 
Input
There multiple test cases in the input, each test case contains two lines.
The first line has two integers, N and k (k<=N<=10^5).
The second line has N integers, a1, a2 ... an. All numbers are ranged in [1, 2000].
 
Output
For every test case, output one single line contains a real number, which is mentioned in the description, accurate to 0.01.
 
题目大意:给n个数和k,求数的个数大于等于k的子段的最大平均值。
思路:可以去看IOI国家集训队论文:《浅谈数形结合思想在信息学竞赛中的应用》——周源
也可以直接看这个http://blog.sina.com.cn/s/blog_ad1f8960010174el.html
 
PS:这就是传说中的来自数据组数的恶意吗,看上去似乎有100组大数据的感觉……G++超时的可以尝试用C++交,HDU的C++读入比G++快,而且优化的程度也不同。
 
代码(C++ 500MS/G++ 906MS):
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cctype>
 6 using namespace std;
 7 typedef long long LL;
 8 
 9 const int MAXN = 100010;
10 
11 int sum[MAXN];
12 int n, k;
13 
14 int readint() {
15     char c = getchar();
16     while(!isdigit(c)) c = getchar();
17     int res = 0;
18     while(isdigit(c)) res = res * 10 + c - '0', c = getchar();
19     return res;
20 }
21 
22 struct Point {
23     int x, y;
24     Point() {}
25     Point(int x, int y): x(x), y(y) {}
26     Point operator - (const Point &rhs) const {
27         return Point(x - rhs.x, y - rhs.y);
28     }
29     double slope() {
30         return (double)y / x;
31     }
32 };
33 
34 LL cross(const Point &a, const Point &b) {
35     return (LL)a.x * b.y - (LL)a.y * b.x;
36 }
37 
38 LL cross(const Point &o, const Point &a, const Point &b) {
39     return cross(a - o, b - o);
40 }
41 
42 Point que[MAXN], p;
43 int head, tail;
44 
45 double solve() {
46     double res = 0;
47     head = 0; tail = -1;
48     for(int i = k; i <= n; ++i) {
49         p = Point(i - k, sum[i - k]);
50         while(head < tail && cross(que[tail - 1], que[tail], p) <= 0) --tail;
51         que[++tail] = p;
52 
53         p = Point(i, sum[i]);
54         while(head < tail && cross(que[head], que[head + 1], p) >= 0) ++head;
55         res = max(res, (p - que[head]).slope());
56     }
57     return res;
58 }
59 
60 int main() {
61     while(scanf("%d%d", &n, &k) != EOF) {
62         for(int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + readint();
63         printf("%.2f\n", solve());
64     }
65 }
View Code

 

posted @ 2014-08-27 00:13  Oyking  阅读(229)  评论(0编辑  收藏  举报