您的位置:首页 > 其它

zoj-1025 Wooden Sticks有关贪心和动态规划

2012-05-05 08:59 239 查看
Wooden Sticks 这道题的大意是加工木棍,按长度length和重量weight,如果前一根木棍的l 和重量w,都小于或等于后一根的length (l' and weight w'),即 if l<=l' and w<=w'.则不需要额外的加工时间,否则setup的加一。

首先,如果按照一般的思路,我们会把l按从小到大排序,然后找最长连续子序列的个数即可。很容易想到!

这里面有两个变量l 和w,最好用结构来储存,这样直接调用C语言的快排就行了。

#include<stdlib.h>

void qsort(void *buf, size_t num, size_t size, int (* compare) (const void * , const void *) );

功能:对buf 指向的数据 ( 包含num 项,每项的大小为 size),进行快速排序,如果函数 compare 的第一个参数小于第二个参数,返回负值;如果等于,返回零值;如果大于返回正值。函数对 buf 指向的数据按升序排序。

找它的最长连续子序列的个数,我用了一个标记数组mark[ ],从前往后查找,初始值mark[ ] 全部为false,遇到符合要求的,则把mark标记为true。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
struct STK
{
int l;
int w;
};
int cmp(const void *a,const void *b)
{
struct STK *c=(struct STK *)a;
struct STK *d=(struct STK *)b;
if(c->l==d->l)
return c->w-d->w;
return c->l-d->l;
}

STK sticks[5002];
bool mark[5002];
int main()
{
int t,n;
int i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;++i)
scanf("%d%d",&sticks[i].l,&sticks[i].w);
qsort(sticks,n,sizeof(STK),cmp);
memset(mark,0,sizeof(mark));
int sum=0; //用于计算setup
int W; //用于记录当前的weight
for(i=0;i<n;i++)
{
if(mark[i])
continue;
sum++;
W=sticks[i].w;
for(j=i+1;j<n;j++)
{
if(mark[j])
continue;
if(W<=sticks[j].w)
{
W=sticks[j].w;
mark[j]=1;
}
}
}
printf("%d\n",sum);
}
return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: