推箱子,遞歸與遞推
阿新 • • 發佈:2019-02-21
tmp 一個數 sta urn pos 遞歸實現 一個 space iostream
遞推代碼
1 #include <vector> 2 #include <iostream> 3 #include <stack> 4 using namespace std; 5 6 const int MAX = 100000000; 7 int h[MAX] = { 0 }; 8 int pre[MAX] = {0}; 9 //用於累計count,如果某個位置有比之前某一個數大的,則比較這個位置的count與之前的數的count的關系 10 int count[MAX] = { 0 }; 11 12 int main() 13{ 14 int n; 15 cin >> n; 16 17 for (int i = 0;i<n;i++) 18 { 19 cin >> h[i]; 20 } 21 22 fill(count,count+MAX,1); 23 24 for(int i=0 ;i<MAX;i++) 25 { 26 pre[i] = i; 27 } 28 29 //記錄最長的子串 30 int max = 0; 31 //記錄最長字串的最大的一個值 32 int maxid = 0; 33 34 for(int i=1;i<n;i++) 35 { 36 //每次遍歷,如果大則取最大的count 37 for(int j=i-1;j>=0;j--) 38 { 39 if(h[i] > h[j] && count[i] < count[j] + 1 ) 40 { 41 count[i] = count[j] + 1; 42 43 pre[i] = j; 44 45 if(max < count[i]) 46 { 47 maxid = i; 48 max = count[i]; 49 } 50 } 51 } 52 } 53 54 cout << max << endl; 55 56 //輸出該子串 57 while(maxid != pre[maxid]) 58 { 59 cout << h[maxid] << " "; 60 maxid = pre[maxid]; 61 } 62 cout << h[maxid] << endl; 63 64 return 0; 65 }
遞歸實現
#include <vector> #include <iostream> #include <stack> using namespace std; const int MAX = 100000000; int h[MAX] = {0}; int num; stack<int> tmp; stack<int> res; stack<int> res1; int maxh = 0; void solve(int *h,int &num,int pos,int len) { if(pos == len) { if(tmp.size() > num) { res = tmp; num = tmp.size(); } return; } for(int i=pos;i<len;i++) { if(h[i] > maxh) { //添加進去 maxh = h[i]; tmp.push(h[i]); solve(h,num,pos+1,len); //回溯 tmp.pop(); if(tmp.size() > 0) { maxh = tmp.top(); } else { maxh = 0; } //不添加進去 ,註意遞歸的下一次位置 solve(h,num,pos+1,len); } else { solve(h,num,pos+1,len); } } } int main() { int n; cin >> n; for(int i=0;i<n;i++) { cin >> h[i]; } int num = 0; solve(h,num,0,n); cout << num << endl; while(!res.empty()) { cout << res.top(); res.pop(); } return 0; }
推箱子,遞歸與遞推