ZOJ1025(简单贪心)

the machine will need no setup time for a stick of length l' and weight w' if l<=l' and w<=w'.

 

#include <iostream>
#include 
<cstdlib>
using namespace std;

const int MAX_SIZE = 5002
;

typedef 
struct

{
    
int
 length;
    
int
 weight;
    
bool mark;//标记是否以加工过

}
Node;

Node stick[MAX_SIZE];
int
 T,n;

int cmp(const void *a, const void *
b)
{//以主关键字length升序排列,次关键字weight升序排列
    Node *p,*q;
    p 
= (Node *
)a;
    q 
= (Node *
)b;
    
if(p->length != q->
length)
        
return p->length > q->
length;
    
else

        
return p->weight > q->weight;
}

void Create()
{
    
for(int i = 0; i < n; i++
)
    
{
        cin
>>stick[i].length>>
stick[i].weight;
        stick[i].mark 
= false;//未加工

    }

}


void Solve()
{
    
int cnt = 0;//由于计已加工的stick

    int ttime = 0;//记录总时间
    int i,j,k;
    Create();
    qsort(stick,n,
sizeof
(Node),cmp);
    
for(i = 0; i < n; i++
)
        
if(stick[i].mark == false
)
        
{
            stick[i].mark 
= true
;
            cnt
++;//对stick[i]进行加工

            k = i;
            j 
= i +1
;
            
for(; j < n; j++
)
                
if(stick[j].mark == false
)
                
if(stick[k].weight <=
 stick[j].weight)
                
{//能贪则贪
                    stick[j].mark = true;cnt++;
                    k 
=
 j;
                }

            ttime
++;
            
if(cnt == n)//已经全部加工

                break;
        }

    cout
<<ttime<<endl;
}


int main()
{
    
while(cin>>
T)
    
{
        
while(T--
)
        
{
            cin
>>
n;
            Solve();
        }

    }

    
return 0;
}

posted on 2009-03-04 15:42  Xredman  阅读(325)  评论(0编辑  收藏  举报

导航