ACM Problem 1001(棍棒问题)

  

  There is a pile of n wooden sticks. The length and weight of each stick are known in advance. The sticks are to be processed by a woodworking machine in one by one fashion. It needs some time, called setup time, for the machine to prepare processing a stick. The setup times are associated with cleaning operations and changing tools and shapes in the machine. The setup times of the woodworking machine are given as follows: 

(a) The setup time for the first wooden stick is 1 minute. 
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l' and weight w' if l<=l' and w<=w'. Otherwise, it will need 1 minute for setup. 

You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are (4,9), (5,2), (2,1), (3,5), and (1,4), then the minimum setup time should be 2 minutes since there is a sequence of pairs (1,4), (3,5), (4,9), (2,1), (5,2).
  
题意是:将木棍放在机器里处理,第一根需要一分钟,剩余的如果大于等于前边放入的长度和重量,就不用费时间,否则再需要一分钟,计算给出一组数的最少时间!用贪心算出最少降序序列个数!
 
输入:3
   5
   4 9 5 2 2 1 3 5 1 4
   3
   2 2 1 1 2 2
   3
   1 3 2 2 3 1
输出:
   2
   1
   3
代码:

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include<string.h>

struct stick
{
  int l;
  int w;
};
bool use[5010];
bool com_s(const stick s1,const stick s2)
{
  if(s1.l != s2.l)
  return s1.l < s2.l;
  else
  return s1.w < s2.w;
}

int choose(vector<stick> & v1,int time)
{
  int num = v1.size();
  memset(use,0,sizeof(use));
  for(int i = 0;i < num;i++)
  {
    stick big = v1[i];
    if(!use[i])
    {
      for(int j = i+1;j < num;j++)
      {
        if(v1[j].w >= big.w&&!use[j])
        {
          use[j] = true;
          big = v1[j];
        }
      }
      time++;
    }
  }
  return time;
}

int main()
{
  vector<stick> v1;
  int t = 0;
  int num = 0;
  cin >> t;
  while(t--)
  {
    cin >> num;
    stick * s1 = new stick[num];
    int time = 0;
    for(int i = 0;i < num;i++)
    {
      cin >> s1[i].l >> s1[i].w;
      use[i] = false;
      v1.push_back(s1[i]);
    }
    sort(v1.begin(),v1.end(),com_s);
    time = choose(v1,time);
    cout << time << endl;
    v1.clear();
    delete []s1;
  }
}

 

思路:首先定义一个棍棒的结构体,然后先按照棍棒长度升序排序,如果长度相同,再按照重量升序排序。用一个数组记录所有棍棒的状态,1代表用过的,0代表还没用过,然后每次比较后,符合后面长度和重量大于前面的长度和重量的棍棒,让其表示为1,因为所需要的时间最多为棍棒的数量,所以每个每个没用过的棍棒比较的次数为棍棒的数量,直到所有棍棒状态变为1。

posted @ 2016-03-19 10:40  SDAU_ZG  阅读(194)  评论(0编辑  收藏  举报