子序列问题
最長子序列
題目鏈接
最短子序列
尺取法
#include<bits/stdc++.h> #define ll long long #define N 100005 int inf = 0x3f3f3f3f; using namespace std; ll n, m, a[N], sum[N]; int main (){while(cin >> n >> m){a[0] = sum[0] = 0;for(int i = 1; i <= n; i++){cin >> a[i];sum[i] =sum[i-1] + a[i]; //讀入并計(jì)算sum[i] sum為遞增序列}int ans = n + 1;for(int i = 1; i <= n; i++){int t = lower_bound(sum + 1 + i, sum + 1 + n, m + sum[i - 1]) - sum;if(t <= n)ans = min(ans, t - i + 1);} if (ans == n + 1) //無解 ans = 0; cout << ans <<endl; } return 0; } #include<bits/stdc++.h> #define ll long long #define N 100005 int inf = 0x3f3f3f3f; using namespace std; ll n, m, a[N], sum[N]; int main (){while(cin >> n >> m){a[0] = sum[0] = 0;for(int i = 1; i <= n; i++){cin >> a[i];sum[i] =sum[i-1] + a[i]; //讀入并計(jì)算sum[i] }int ans = n + 1;int s = 0, e = 1;while(sum[e] - sum[s] < m){e ++;}while(e <= n){ // while(sum[e] - sum[s] < m && e <= n) { //要加上 e <= n,費(fèi)則會 runtime error // e ++; // }while(sum[e] - sum[s] >= m){ //更新最小序列 s ++;}ans = min(ans, e - s + 1);e ++; //枚舉下一個數(shù) s ++;}if (ans == n + 1) //無解ans = 0; cout << ans <<endl; } return 0; } #include<bits/stdc++.h> #define ll long long #define N 100005 int inf = 0x3f3f3f3f; using namespace std; ll n, m, a[N], sum[N]; int main (){while(cin >> n >> m){for(int i = 1; i <= n; i++){cin >> a[i];}int ans = n + 1;int s = 1, e = 1;ll sum = 0;while(1){while(sum < m && e <= n){sum += a[e++];}if(sum < m)break;ans = min(ans, e - s);sum -= a[s++];}if (ans == n + 1) //無解ans = 0; cout << ans <<endl; } return 0; }總結(jié)
- 上一篇: 埃森哲杯第十六届上海大学程序设计联赛春季
- 下一篇: STL-二分查找