uva 1451 数形结合


思路:枚举点t,寻找满足条件的点t';

计sum[i]为前i项合,平均值即为sum[t]-sum[t'-1]/t-t'+1

设(Pi=(i,Si),表示点在s中的位置,那么就可以画出坐标图,问题就转化为斜率最大;

于是画图分析。

几个点之间只有上凸下凸两种情况,取3个点为符合条件(t-t'>=L)的t',分析后得结论上凸点在各种情况(t)下都要舍去;

于是就可以不断更新,更新策略为新插入点,删除掉原来是下凸点,插入后变成上凸点的点;

随着t增大,t'只会增大(t增大,pt增大),所以增加到斜率变小时即可停止;

而且对于某个Pt,选好切点后,对于之后的Pt,之前的点Pt'都不会用到了,于是不用从头枚举

代码

#include<cstdio>
using namespace std;

const int maxn = 100000 + 5;

int n, L;
char s[maxn];
int sum[maxn], p[maxn]; // average of i~j is (sum[j]-sum[i-1])/(j-i+1)

// compare average of x1~x2 and x3~x4    //x1-x2的斜率大于x3-x4返回1
int compare_average(int x1, int x2, int x3, int x4) {
  return (sum[x2]-sum[x1-1]) * (x4-x3+1) - (sum[x4]-sum[x3-1]) * (x2-x1+1);
}

int main() {
  int T;
  scanf("%d", &T);

  while(T--) {
    scanf("%d%d%s", &n, &L, s+1);

    sum[0] = 0;
    for(int i = 1; i <= n; i++) sum[i] = sum[i-1] + s[i] - '0';

    int ansL = 1, ansR = L;

    // p[i..j) is the sequence of candidate start points
    int i = 0, j = 0;   //j是起始点中最右边的点,p[j]代表那个点在序列中的位置
    for (int t = L; t <= n; t++) { // end point ,枚举的右端点
      while (j-i > 1 && compare_average(p[j-2], t-L, p[j-1], t-L) >= 0) j--; // remove concave points
      //t-l是新加的点(上一步t-l+1,而for循环t++了),j-1(上一步j++了)是原来最右边的点,从最右边开始判断是否上凸

      p[j++] = t-L+1; // new candidate   //注意上一个循环已经去掉了右面的上凸点(j--)

      while (j-i > 1 && compare_average(p[i], t, p[i+1], t) <= 0) i++; // update tangent point切点

      int c = compare_average(p[i], t, ansL, ansR);  //更新
      if (c > 0 || c == 0 && t - p[i] < ansR - ansL) {
        ansL = p[i]; ansR = t;
      }
    }
    printf("%d %d
", ansL, ansR);
  }
  return 0;
}
原文地址:https://www.cnblogs.com/lqerio/p/9739593.html