您的位置:首页 > 移动开发

CSU 1098: Happy watering(线段树)

2012-08-12 17:05 337 查看
题意:。。。

每一次找最矮的更新,如果不更新最矮的,则最小值不变,其他的值增大了也没有用。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>

using namespace std;
const int N = 100009;
const int INF = 0x3f3f3f3f;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
int re
,tree[N<<2];
int n,m,ma,mi=INF;
void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d%d",&tree[rt],&re[l]);
        ma=max(ma,tree[rt]);
        mi = min(mi,tree[rt]);
        return ;
    }
    int mid = (l+r)>>1;
    build(lson);
    build(rson);
    tree[rt] = min(tree[rt<<1],tree[rt<<1|1]);
}
void update(int l,int r,int rt)
{
    if(l==r)
    {
        tree[rt]+=re[l];
        ma=max(ma,tree[rt]);
        return;
    }
    int mid = (l+r) >>1;
    if(tree[rt<<1]<tree[rt<<1|1])
    update(lson);
    else
    update(rson);
    tree[rt] = min(tree[rt<<1],tree[rt<<1|1]);
}
int fin(int l,int r,int rt)
{
    if(l==r)
    {
        return tree[rt];
    }
    int mid = (l+r) >>1;
    if(tree[rt<<1]<tree[rt<<1|1])
    return fin(lson);
    else
    return fin(rson);
}
int ans;
void deal()
{
    update(1,n,1);
    mi = fin(1,n,1);//cout<<mi<<" "<<ma<<endl;
    ans=min(ans,ma-mi);
}
int main()
{
    freopen("in.txt","r",stdin);
    while(~scanf("%d%d",&n,&m))
    {
        ans = INF;
        ma = -1;
        mi = INF;
        build(1,n,1);
        //cout<<mi<<" "<<ma<<endl;
        ans=ma-mi;
        while(m--)
        deal();
        printf("%d\n",ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: