【练习12】 贪心算法 1002 今年暑假不AC

来源:互联网 发布:淘宝刷到一钻 编辑:程序博客网 时间:2024/05/22 02:19
兼有动态规划和贪心的思想。
一维数组里保存的的就是以当前节目作为开始,最多能完整地看多少个不同的节目。
很明显,播出时间最晚的节目只是能1。
我采取从后往前的规划方法。
这样,当循环到i时,能保证数组里 D[i+1] -> D[n-1] 保存的都是最优解。
所以让j 从 i+1 到 n-1 循环,找出看完第i个节目后最多还能看的节目数max。(不要忘了判断能否完整收看哦)

把max+1 保存到 D[i]里。如此下去直到结束。 

另外,熟悉qsort的用法也能很大程度上提高自己写代码的效率。

//模板开始#include <string>   #include <vector>   #include <algorithm>   #include <iostream>   #include <sstream>   #include <fstream>   #include <map>   #include <set>   #include <cstdio>   #include <cmath>   #include <cstdlib>   #include <ctime>#include<iomanip>#define SZ(x) (int(x.size()))using namespace std;int toInt(string s){istringstream sin(s); int t; sin>>t; return t;}template<class T> string toString(T x){ostringstream sout; sout<<x; return sout.str();}typedef long long int64;int64 toInt64(string s){istringstream sin(s); int64 t; sin>>t;return t;}template<class T> T gcd(T a, T b){ if(a<0) return gcd(-a, b);if(b<0) return gcd(a, -b);return (b == 0)? a : gcd(b, a % b);}//模板结束(通用部分)//hdoj专题 贪心算法 1001 FatMouse' Trade#define MAXN 105#include <cstdlib>typedef struct T{int s, e;};int cmp( const void *_p, const void *_q){T *p = ( T *)_p;T *q = ( T *)_q;return p -> s - q -> s;}int main(){T t[MAXN];int n;int dp[MAXN];ifstream ifs("shuju.txt", ios::in);while(cin>>n && n != 0)//ifsifs>>n{for(int i = 0; i < n; i++){//ifs>>t[i].s>>t[i].e;cin>>t[i].s>>t[i].e;}qsort( t, n, sizeof t[0], cmp);memset(dp, 1, n);dp[n - 1] = 1;for(int i = n - 2; i >= 0; i--){for(int j = i + 1; j < n; j++){if(t[i].e <= t[j].s){if(dp[j] + 1 > dp[i + 1]){dp[i] = dp[i + 1] + 1;break;}}dp[i] = dp[i + 1];continue;}}cout<<dp[0]<<endl;}return 0;}