标签:int pair pre ble ++i uva 前缀 stack 超时
题意:给定一个01序列,让你找出一个长度大于等于F的连续子序列使得平均值最大。
析:直接枚举肯定是O(n^3),超时,然后用前缀和来优化,O(n^2),还是太大,这个要求的平均值是 i > j (sum[i] - sum[j-1]) / (i-(j-1)),这正好就是一个斜率的表示形式,可以考虑用优化,每次在加入一个新点的时候把不成立的全部删除,然后再加入,维护一个下凸线。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e16; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e5 + 10; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int q[maxn]; char s[maxn]; int sum[maxn]; bool judge(int i, int j, int k){ return (LL)(sum[i]-sum[j])*(i-k) >= (LL)(sum[i]-sum[k])*(i-j); } int main(){ int T; cin >> T; while(T--){ scanf("%d %d", &n, &m); scanf("%s", s+1); for(int i = 1; i <= n; ++i) sum[i] = sum[i-1] + s[i] - ‘0‘; int fro = 0, rear = 0; int ansL = 1, ansR = m; double ans = 0.0; for(int i = m; i <= n; ++i){ while(fro + 1 < rear && judge(i-m, q[rear-1], q[rear])) --rear; q[++rear] = i - m; while(fro + 1 < rear && judge(i, q[fro+2], q[fro+1])) ++fro; double c = (double)(sum[i]-sum[q[fro+1]])/(i-q[fro+1]); if(ans < c || ans == c && ansR - ansL + 1> i - q[fro+1]){ ans = c; ansL = q[fro+1] + 1; ansR = i; } } printf("%d %d\n", ansL, ansR); } return 0; }
简单的枚举算法可以这样描述:每次枚举一对满足条件的(a, b),即 a≤b-F+1,检查 ave(a, b),并更新当前最大值。然而这题中 N 很大,N 2 的枚举算法显然不能使用,但是能不能优化一下这个效率不高的算法呢?答案是肯定的。目标图形化首先一定会设序列 a i 的部分和:S i =a 1 +a 2 +…+a i , ,特别的定义 S 0 =0。这样可以很简洁的表示出目标函数) 1 () , (1? ??=?i jS Sj i avei j!如果将 S 函数绘在平面直角坐标系内,这就是过点 S j 和点 S i-1 直线的斜率!于是问题转化为:平面上已知 N+1 个点,P i (i, S i ),0≤i≤N,求横向距离大于等于 F 的任意两点连线的最大
标签:int pair pre ble ++i uva 前缀 stack 超时
原文地址:http://www.cnblogs.com/dwtfukgv/p/7294492.html