心急的C小加-OJ

来源:互联网 发布:画梁图软件 编辑:程序博客网 时间:2024/05/22 07:21

心急的C小加

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述

C小加有一些木棒,它们的长度和质量都已经知道,需要一个机器处理这些木棒,机器开启的时候需要耗费一个单位的时间,如果第i+1个木棒的重量和长度都大于等于第i个处理的木棒,那么将不会耗费时间,否则需要消耗一个单位的时间。因为急着去约会,C小加想在最短的时间内把木棒处理完,你能告诉他应该怎样做吗?

输入
第一行是一个整数T(1<T<1500),表示输入数据一共有T组。
每组测试数据的第一行是一个整数N(1<=N<=5000),表示有N个木棒。接下来的一行分别输入N个木棒的L,W(0 < L ,W <= 10000),用一个空格隔开,分别表示木棒的长度和质量。
输出
处理这些木棒的最短时间。
样例输入
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 
样例输出
21

3


个人理解:根据上次讲到的sort()函数,这题有很明显的时间限制,如狗用一般的排序,时间很有可能会超时,所以,可以先用函数排序,之后再用贪心进行。

结果时间内存语言Accepted448272C++

代码:

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


  struct stick
  {
      int len;
      int weight;
  }a[5001];


  bool cmp(stick p, stick q)
  {
      if(p.len == q.len)
          return p.weight < q.weight;
      else
          return p.len < q.len;
  }


  int solve(int n)
  {
      int t, cnt = 0;
      for(int i = 0; i < n; ++i)
      {
          if(a[i].weight)
          {
              ++cnt;
              t = a[i].weight;
              a[i].weight = 0;
              for(int j = i + 1; j < n ;++j)
              {
                  if(a[j].weight >= t)
                  {
                      t = a[j].weight;
                      a[j].weight = 0;
                  }
              }
          }
      }
     return cnt;
 }


 int main()
 {
     int T, n;
     scanf("%d", &T);
     while(T--)
     {
     scanf("%d", &n);
         for(int i = 0; i < n; ++i)
             scanf("%d%d", &a[i].len, &a[i].weight);
         sort(a, a + n, cmp);
         printf("%d\n", solve(n));
  }
     return 0;
 }

原创粉丝点击