码迷,mamicode.com
首页 > 其他好文 > 详细

HDU2795 Billboard 线段树

时间:2015-08-26 15:51:02      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:acm   hdu   c++   线段树   暴力求解   

开始的代码,暴力求解。。。。。果断超时

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;

const int maxn = 200005;

int main()
{
    int  h, w, k, b;
    int  a[maxn] ;
    bool flag;
    while(scanf("%d%d%d", &h, &w, &k) != EOF){
        memset(a, 0, sizeof(a));
        for(int j = 0; j < k; j++){
            scanf("%d", &b);
            flag = false;
            for(int i = 1; i <= h; i++){
                if(a[i] + b <= w) {
                    a[i] += b;
                    flag = true;
                    printf("%d\n", i);
                    break;
                }
            }
            if(!flag) printf("-1\n");
        }
    }
    return 0;
}


线段树求解  

#include<iostream>
#include<cstdio>
using namespace std;
const int  N = 200005;
int h,w,n;
struct  Tree
{
    int l,r;
    int num;
}tree[N<<2];
int minn(int h,int n)
{
    if(h>n)
        return n;
    else
        return h;
}
int maxx(int a,int b)
{
    if(a>b)
        return a;
    else
        return b;
}
void creat(int i,int l,int r)
{
    int mid=(l+r)>>1;
    tree[i].l=l;
    tree[i].r=r;
    tree[i].num=w;
    if(l==r)
        return;
    creat(i<<1,l,mid);
    creat(i<<1|1,mid+1,r);
}
int query(int i,int len)
{
    if(tree[i].l==tree[i].r)
    {
        tree[i].num-=len;
        return tree[i].l;
    }
    else
    {
        int sum1=0,sum2=0;
        if(len<=tree[i<<1].num)
            sum1=query(i<<1, len);
        else
            if(len<=tree[i<<1|1].num)
                sum2=query(i<<1|1,len);
        tree[i].num=maxx(tree[i<<1].num,tree[i<<1|1].num);   //回溯
        return sum1+sum2;
    }
}
int main()
{
    while(scanf("%d%d%d",&h,&w,&n) != EOF)
    {
        int len;
        creat(1,1,minn(h,n));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&len);
            if(tree[1].num>=len)
                printf("%d\n",query(1,len));
            else
                printf("-1\n");
        }
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU2795 Billboard 线段树

标签:acm   hdu   c++   线段树   暴力求解   

原文地址:http://blog.csdn.net/efine_dxq/article/details/48003761

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!