如果当前要做的木板的宽度和长度都不小于前面做的一个,则做现在这个木板不用花时间,
输入很多木板的长与宽,求做这些木板所花的最短时间,否则需要一分钟
贪心法
#include<iostream>
using namespace std;
typedef struct stick
{
int length;
int weight;
bool flag;
}Stick;
bool compare(const Stick &a,const Stick &b)
{
if(a.length<=b.length && a.weight<=b.weight)
return true;
else
return false;
}
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
int PartTion(Stick a[],int low,int high)
{
Stick x=a[high];
int i=low-1;
for(int j=low;j<high;j++)
if(a[j].length<=x.length || a[j].length==x.length && a[j].weight<=x.weight)
{
i++;
swap(a[i].length,a[j].length);
swap(a[i].weight,a[j].weight);
}
swap(a[i+1].length,a[high].length);
swap(a[i+1].weight,a[high].weight);
return i+1;
}
void QuickSort(Stick a[],int low,int high)//快速排序
{
if(low<high)
{
int q=PartTion(a,low,high);
QuickSort(a,low,q-1);
QuickSort(a,q+1,high);
}
}
int main()
{
int Tgroups;
cout<<"Enter T: ";
cin>>Tgroups;
Stick wooden[5000];
while(Tgroups--)
{
int i=0;
int testNum;
cout<<endl<<"Enter testNum: ";
cin>>testNum;
cout<<"Enter length and weight: ";
for(;i!=testNum;++i)
{
cin>>wooden[i].length>>wooden[i].weight;
wooden[i].flag=true;
}
QuickSort(wooden,0,testNum-1);
int minutes=0;
for(i=0;i<testNum;i++)
if(wooden[i].flag==true)
{
Stick temp=wooden[i];
for(int j=i+1;j!=testNum;j++)
if(wooden[j].flag==true && compare(temp,wooden[j]))
{
temp=wooden[j];
wooden[j].flag=false;
}
++minutes;
}
cout<<minutes;
}
return 0;
}