算法分析第十次作业
1. 问题
给出n个节目,给出每个节目开始时间和结束时间,同一时间段只能播放一个节目,问最多可以播放多少节目
2. 解析
贪心策略是按结束时间从小到大排序,贪心选择和最后一个节目相容的节目,最后得到就是的答案
3. 设计
排序方式
1 struct node { 2 int l,r; 3 bool operator <(const node &a){ 4 return r<a.r; 5 } 6 }t[maxn];
选择方式
1 sort(t+1,t+n+1); 2 puts("选择:"); 3 int l=0; 4 for(int i=1;i<=n;i++){ 5 if(t[i].l>=l) printf("%d %d\n",t[i].l,t[i].r),l=t[i].r; 6 }
4. 分析
O(n)
5. 源码
https://github.com/Tinkerllt/algorithm-work.git
1 #include<stdio.h> 2 #include<stdio.h> 3 #include<iostream> 4 #include<cmath> 5 #include<cstring> 6 #include<algorithm> 7 #include<bitset> 8 #include<set> 9 #include<deque> 10 #include<queue> 11 #include<vector> 12 //#include<unordered_map> 13 #include<map> 14 #include<stack> 15 using namespace std; 16 #define ll long long 17 #define ull unsigned long long 18 #define pii pair<int,int> 19 #define Pii pair<ll,int> 20 #define m_p make_pair 21 #define l_b lower_bound 22 #define u_b upper_bound 23 const int inf = 0x3f3f3f3f; 24 const ll linf = 0x3f3f3f3f3f3f3f3f; 25 const int maxn = 3e5 + 11; 26 const int maxm = 600 + 11; 27 const int mod = 1e9 + 7; 28 const double eps = 1e-5; 29 inline ll rd() { ll x = 0, f = 1; char ch = getchar(); while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }while (ch >= '0'&&ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }return x * f; } 30 inline ll qpow(ll a, ll b, ll p) { ll res = 1; while (b) { if (b & 1) { res *= a; res %= p; }b >>= 1; a = a * a%p; }return res; } 31 inline ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a%b); } 32 //iterator 33 //head 34 //priority_queue 35 struct node { 36 int l,r; 37 bool operator <(const node &a){ 38 return r<a.r; 39 } 40 }t[maxn]; 41 int main(){ 42 int n=rd(); 43 for(int i=1;i<=n;i++){ 44 t[i].l=rd(),t[i].r=rd(); 45 } 46 sort(t+1,t+n+1); 47 puts("选择:"); 48 int l=0; 49 for(int i=1;i<=n;i++){ 50 if(t[i].l>=l) printf("%d %d\n",t[i].l,t[i].r),l=t[i].r; 51 } 52 }