分治法 区间的价值 hdu5696

传送门:点击打开链接

题意:给你一个序列,定义一个区间的价值是,这个区间里的最大值乘以最小值。求出所有区间长度对应的最大价值。注意数据为全随机

思路:重点是数据全部随机。这道题有了这个条件后,才变成了很多种方法都能做的题,这里我讲下分治法来搞。。

我们来约定solve(l,r)来求出区间[l,r]中各种区间长度的最大价值。

然后,我们找出[l,r]中的最小值。

固定了最小值以后,我们再去枚举最大值,算出各个价值。

我们能发现,随着区间变长,如果最小值是固定的,那么最大值只有可能越来越大,价值也会越来越大。

所以我们要把区间短的答案给区间长的更新。

如果最小值不是这一个呢?我们直接递归两边的就行了

我们再递归继续求solve(l,p-1)和solve(p+1,r),p是最小值的位置

由于数据是全随机的,所以不会退化到O(n^2)

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout<<"["<<x<<"]";
#define FIN freopen("input.txt","r",stdin);
#define FOUT freopen("output.txt","w+",stdout);
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 1e5 + 5;
const int mod = 1e9 + 7;

int n, A[MX];
LL temp[MX], ans[MX];
void umax(LL &a, LL b) {
    a = max(a, b);
}
void solve(int l, int r) {
    if(l > r) return;
    int p = 0;
    for(int i = l; i <= r; i++) {
        if(!p || A[i] < A[p]) p = i;
    }
    int w = r - l + 1;
    for(int i = 1; i <= w; i++) temp[i] = 0;
    for(int i = l; i <= p; i++) {
        umax(temp[p - i + 1], (LL)A[p]*A[i]);
    }
    for(int i = p; i <= r; i++) {
        umax(temp[i - p + 1], (LL)A[p]*A[i]);
    }
    LL max_pre = 0;
    for(int i = 1; i <= w; i++) {
        umax(max_pre, temp[i]);
        umax(ans[i], max_pre);
    }
    solve(l, p - 1);
    solve(p + 1, r);
}
int main() {
    //FIN;
    while(~scanf("%d", &n)) {
        memset(ans, 0, sizeof(ans));
        for(int i = 1; i <= n; i++) {
            scanf("%d", &A[i]);
        }
        solve(1, n);
        for(int i = 1; i <= n; i++) {
            printf("%I64d\n", ans[i]);
        }
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值