开始的代码,暴力求解。。。。。果断超时 #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;
}