Gym 101201H Paint (离散化+DP)
Posted dwtfukgv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Gym 101201H Paint (离散化+DP)相关的知识,希望对你有一定的参考价值。
题意:给定 n 个区间,让你选出一些,使得每个选出区间不交叉,并且覆盖区间最大。
析:最容易想到的先是离散化,然后最先想到的就是 O(n^2)的复杂度,dp[i] = max(dp[j] + a[i].r - a[i].l) 区间不相交,这个可以用线段树来维护一个最大值,因为有区间性,但是也可以不用线段树,直接进行线性DP,因为要选的区间越多越好,相比而言,有就要选,但是有更优的就选最优的。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #include <list> #include <assert.h> #include <bitset> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define fi first #define se second #define pb push_back #define sqr(x) ((x)*(x)) #define ms(a,b) memset(a, b, sizeof a) #define sz size() #define pu push_up #define pd push_down #define cl clear() #define all 1,n,1 #define FOR(i,x,n) for(int i = (x); i < (n); ++i) #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 1e20; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 2e5 + 50; const LL mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c) { return r >= 0 && r < n && c >= 0 && c < m; } struct Node{ LL l, r; bool operator < (const Node &p) const{ return l < p.l || l == p.l && r < p.r; } }; map<LL, int> mp; Node a[maxn]; vector<LL> v; LL dp[maxn<<1]; int main(){ LL n; scanf("%I64d %d", &n, &m); for(int i = 0; i < m; ++i){ scanf("%I64d %I64d", &a[i].l, &a[i].r); ++a[i].r; v.pb(a[i].l); v.pb(a[i].r); } sort(a, a + m); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); for(int i = 0; i < v.sz; ++i) mp[v[i]] = i; int idx = 0; LL ans = 0; for(int i = 0; i < v.sz; ++i){ dp[i+1] = max(dp[i+1], dp[i]); while(idx < m && mp[a[idx].l] == i){ int r = mp[a[idx].r]; dp[r] = max(dp[r], dp[i] + a[idx].r - a[idx].l); ++idx; } ans = max(ans, dp[i]); } printf("%I64d\n", n - ans); return 0; }
以上是关于Gym 101201H Paint (离散化+DP)的主要内容,如果未能解决你的问题,请参考以下文章
每日dp Gym - 101889E Enigma 数位dp 记忆化搜索
AOJ 0531:Paint Color(二维离散+imos)
Loppinha, the boy who likes sopinha Gym - 101875E (dp,记忆化搜索)