POJ1051 木棍叠加

题目详见http://acm.hdu.edu.cn/showproblem.php?pid=1051  意思就是说如果机器要处理叠加的木棍。第一个木棍处理时候机器需要时间调整,如果下个叠加的木棍的长度和重量都大于等于底下的木棍,则机器不需要调整时间,直接叠加上面即可。否则机器需要重新调整,这需要时间。给你一堆木棍的长度和重量,希望你调整木棍的叠加顺序,使机器的调整时间最短。
 很明显是贪心算法,首先对木棍进行排序,长度为主,重量为辅,从小到大的排序。给每一个木棍一个增加一个标志位,标志木棍是否已经叠加过了。。
 第一个木棍要叠加,这就是贪心,然后每次寻找可以叠加在之前木棍上的木棍。
 每次的遍历都是寻找木棍未处理序列的最长非递减子序列。

include <iostream>  
#include<algorithm> 
#include<vector>
using namespace std;

typedef  struct Stick
{	
	int length;
	int weight;
	bool flag;
}Stick; 
bool MinToMax(const Stick& a ,const Stick& b);

int main()
{	
	int T,n;
	int i,j,k;
	int times;
	Stick temp; 
	vector<Stick> stick;
	cin>>T;
	while(T--)
	{
		cin>>n;
		i=n;
		times=0;
		stick.clear();
		while(i--)
		{
			cin>>temp.length;
			cin>>temp.weight;	
			temp.flag=0;
			stick.push_back(temp);
		}
		sort(stick.begin(),stick.end(),MinToMax);
		for(i=0;i<n;i++)
		{
			if(0==stick[i].flag)
			{
				stick[i].flag=1;
				k=i;
				times++;
				for(j=i+1;j<n;j++)
				{
					if(0==stick[j].flag)
					{
						if((stick[j].length>=stick[k].length)&&(stick[j].weight>=stick[k].weight))
						{
							stick[j].flag=1;
							k=j;
						}
					}
				}
			}
		}
		cout<<times<<endl;
	}
	return 0;
}

bool MinToMax(const Stick& a ,const Stick& b)
{
	if (a.length<b.length)   //长度为主,重量为辅助
		return true;
	else if(a.length==b.length)
	{
		if(a.weight<=b.weight)
			return true;
	}
	return false;
}
转载请注明http://blog.csdn.net/liangbopirates/article/details/10042853

你可能感兴趣的:(杭电,贪心算法,1051,hdoj,木棍叠加)