NYOJ236 心急的C小加

心急的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 
样例输出
2
1
3


  1 /*
  2 代码一: ----TLE
  3 思路: 动态规划---- 先按照长度排序,然后根据重量求最长递减子序列
  4 即为所求,可惜超时了
  5 
  6 #include <cstdio>
  7 #include <iostream>
  8 #include <algorithm>
  9 using namespace std;
 10 
 11 struct stick
 12 {
 13     int len;
 14     int weight;
 15 }a[5001];
 16 
 17 bool cmp(stick p, stick q)
 18 {
 19     if(p.len == q.len)
 20         return p.weight < q.weight;
 21     else
 22         return p.len < q.len;
 23 }
 24 
 25 int solve(int n)
 26 {
 27     int dp[5001];
 28     int max = -1;
 29     for(int i = 0; i < n; ++i)
 30     {
 31         dp[i] = 1;
 32         for(int j = 0; j < i ;++j)
 33         {
 34             if(a[i].weight < a[j].weight && dp[j] + 1 > dp[i])
 35                 dp[i] = dp[j] + 1;
 36             if(dp[i] > max)
 37                 max = dp[i];
 38         }
 39     }
 40     return max;
 41 }
 42 
 43 int main()
 44 {
 45     int T, n;
 46     scanf("%d", &T);
 47     while(T--)
 48     {
 49         scanf("%d", &n);
 50         for(int i = 0; i < n; ++i)
 51             scanf("%d%d", &a[i].len, &a[i].weight);
 52         sort(a, a + n, cmp);
 53         printf("%d\n", solve(n));
 54     }
 55     return 0;
 56 }
 57 
 58 */
 59 代码二:----AC
 60 思路:先排序,然后根据贪心原则依次过滤
 61 #include <cstdio>
 62 #include <iostream>
 63 #include <algorithm>
 64 using namespace std;
 65 
 66 struct stick
 67 {
 68     int len;
 69     int weight;
 70 }a[5001];
 71 
 72 bool cmp(stick p, stick q)
 73 {
 74     if(p.len == q.len)
 75         return p.weight < q.weight;
 76     else
 77         return p.len < q.len;
 78 }
 79 
 80 int solve(int n)
 81 {
 82     int t, cnt = 0;
 83     for(int i = 0; i < n; ++i)
 84     {
 85         if(a[i].weight)
 86         {
 87             ++cnt;
 88             t = a[i].weight;
 89             a[i].weight = 0;
 90             for(int j = i + 1; j < n ;++j)
 91             {
 92                 if(a[j].weight >= t)
 93                 {
 94                     t = a[j].weight;
 95                     a[j].weight = 0;
 96                 }
 97             }
 98         }
 99     }
100     return cnt;
101 }
102 
103 int main()
104 {
105     int T, n;
106     scanf("%d", &T);
107     while(T--)
108     {
109         scanf("%d", &n);
110         for(int i = 0; i < n; ++i)
111             scanf("%d%d", &a[i].len, &a[i].weight);
112         sort(a, a + n, cmp);
113         printf("%d\n", solve(n));
114     }
115     return 0;
116 }
功不成,身已退
原文地址:https://www.cnblogs.com/dongsheng/p/2879724.html