Increasing Subsequence (hard version)
题目链接:https://codeforces.com/contest/1157/problem/C2
首先讲一下题目大意:给你n个数,然后从最左边(L)或者最右边(R)取一个数生成出一个新的序列,对于这个序列的要求是递增的(注意是递增的,不能存在等于的情况)问这个序列有多长。并打印此操作。
这题就是忘了,这个序列不能存在相同的情况,导致wa了几发。
思路:就是采取贪心的策略,贪心的策略是比较这个序列的最左端或最右端,谁小就取谁,当两个相等的情况就看谁的序列更长,如果出现两个序列都一样长,就要比较最后的字母谁大谁小了。用两个下标来控制这个要取得序列位置。当然别忘了,比较的时候你要看生成的新序列中最后一个元素和你要取的数比较,是不是满足加进来的数要比新序列中的数大。所以这题就是情况讨论比较多,思想很简单。下面是我写的代码,不喜勿喷。时间复杂度是O(n)
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <queue> 5 #include <map> 6 #include <cstring> 7 #include <string> 8 #include <set> 9 #include <vector> 10 #include <list> 11 #include <deque> 12 #include <algorithm> 13 #include <stack> 14 #include <numeric> 15 #include <time.h> 16 #include<iomanip> 17 #include<sstream> 18 #pragma disable:4996) 19 using namespace std; 20 const long long inf = 0x7f7f7f7f; 21 long long GCD(long long a, long long b) { return 0 == b ? a : GCD(b, a%b); } 22 const long long mod = 1e9 + 7; 23 const double pi = acos(-1); 24 int str[210000]; 25 int main() 26 { 27 ios_base::sync_with_stdio(false); 28 int n; 29 cin >> n; 30 for (int i = 0; i < n; i++) 31 cin >> str[i]; 32 vector<int>q; 33 int k = n - 1; 34 int a = -1; 35 for (int i = 0; i < n; ) 36 { 37 if (str[i] < str[k] && a < str[i]) 38 q.push_back(1), a = str[i], i++; 39 else if (str[i] == str[k] && a < str[k]) 40 { 41 int ans1 = 0, ans2 = 0; 42 for (int j = i + 1; j <= k; j++) 43 { 44 if (str[j - 1] < str[j]) 45 ans1++; 46 else 47 break; 48 } 49 for (int j = k - 1; j >= i; j--) 50 if (str[j + 1] < str[j]) 51 ans2++; 52 else 53 break; 54 if (ans1 < ans2) 55 { 56 a = str[k - ans2]; 57 for (int j = 0; j <= ans2; j++) 58 q.push_back(0), k--; 59 } 60 else if (ans1 == ans2) 61 { 62 if (str[i + ans1] > str[k - ans2]) 63 { 64 a = str[k - ans2]; 65 for (int j = 0; j <= ans2; j++) 66 q.push_back(0), k--; 67 } 68 else 69 { 70 a = str[i + ans1]; 71 for (int j = 0; j <= ans1; j++) 72 q.push_back(1), i++; 73 } 74 } 75 else 76 { 77 a = str[i + ans1]; 78 for (int j = 0; j <= ans1; j++) 79 q.push_back(1), i++; 80 } 81 } 82 else if (str[i] > str[k] && a < str[k]) 83 q.push_back(0), k--, a = str[k + 1]; 84 else 85 { 86 if (a < str[i]) 87 q.push_back(1), a=str[i],i++; 88 else if (a < str[k]) 89 q.push_back(0),a=str[k], k--; 90 else 91 break; 92 } 93 if (i > k) 94 break; 95 } 96 cout << q.size() << endl; 97 for (int i = 0; i < q.size(); i++) 98 if (q[i] == 0) 99 cout << "R"; 100 else 101 cout << "L"; 102 }