學大偉業 Day 4 培訓總結
阿新 • • 發佈:2018-02-26
完全 今天 void 經典 01背包 轉移 給定 can ace
今天講的全是dp...
不多廢話,先看一道經典的模板LIS(最長不下降子序列)
一.LIS
給定一個長度為N的數列,求最長上升子序列
例:1 7 2 8 3 4
答案:1 2 3 4
代碼:
1 #include <bits/stdc++.h>//突然想用萬能庫 2 3 using namespace std; 4 5 const int maxn = 100000; 6 int n, data[maxn], dp[maxn], from[maxn];//方案 7 void output(int x) 8 { 9 if(!x) return ; 10 output(from[x]); 11 cout<<data[x]<<" "; 12 } 13 int main() 14 { 15 cin>>n; 16 for(int i = 1; i <= n;i++) cin>>data[i]; 17 18 for(int i = 1; i <= n;i++) 19 { 20 dp[i] = 1; 21 from[i] = 0; 22 for(int j = 1; j < i; j++) 23 { 24if(data[j] < data[i]&&dp[j]+1 > dp[i]) 25 { 26 dp[i] = dp[j] + 1; 27 from[i] = j; 28 } 29 } 30 } 31 32 int ans = dp[1], pos = 1; 33 for(int i = 1; i <= n; i++) 34 if(ans < dp[i])35 { 36 ans = dp[i]; 37 pos = i; 38 } 39 cout<<ans<<endl; 40 output(pos); 41 return 0; 42 }
二.背包問題
背包就不多講了,背包九講裏面非常明白了,也是很基礎的dp
N個物品,每個物品有價值和體積兩個屬性
從中選出若幹個物品,體積和不超過V 要求選出的物品價值和最大
每個物品只能選一次(01背包)
體積可能是多維(多維背包)
物品可以被選的次數可能是有限次或者無限次(完全背包)
物品之間可能存在依賴(依賴背包)
......
三.ST表
思想:倍增、DP(狀態轉移方程: F[i,j] = min/max (F[i,j - 1],F[i + 2^(j - 1),j - 1]) )
功能:求任意區間的最大值
要求:靜態的,無法修改數據
空間復雜度:O(nlogn)
時間復雜度:O(nlogn) – O(1)
#include <cstdio> #include <algorithm> using namespace std; int const maxn = 1000000; int st[maxn][20], a[maxn], ans[maxn]; int n, m, left, right, j, i; int main() { scanf("%d%d", &n, &m); for(i = 1; i <= n; i++) { scanf("%d", &a[i]); st[i][0] = a[i]; } for(j = 1; (1<<j) <= n; j++) for(i = 1; i <= n-(1<<j) + 1; i++) st[i][j] = min(st[i][j-1] , st[i+( 1<<(j-1) )][j-1]); for(i = 1; i <= m; i++) { scanf("%d%d", &left, &right); j = 0; while((1<<(j+1)) <= (right-left+1)) j++; ans[i] = min(st[left][j],st[right-(1<<j)+1][j]); } for(i = 1; i <= m; i++) printf("%d ",ans[i]); return 0; }
還有一部分...待我再細細思考總結...(說白了就是現在還不太明白)
學大偉業 Day 4 培訓總結