*【POJ - 3061】 Subsequence (尺取或二分)
題干:
A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
Input
The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.
Output
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
Sample Input
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5Sample Output
2 3?
解題報告:
? ?這題貌似二分或者尺取法都可以。
AC代碼:(二分)
#include<iostream> #include<cstring> #include<algorithm> #define ll long long using namespace std;ll a[100005]; ll er[100005]; int main() {int t;ll n,s;ll l,r;int minn;cin >> t;while(t--){memset(a,0,sizeof(a));cin >> n >> s;for(int i=1;i<=n;i++){scanf("%lld",&a[i]);a[i]=a[i-1]+a[i];er[i]=n; } // cout << a[n] << endl;if(a[n]<s){cout << 0 << endl;continue;}for(ll i=1;a[n]-a[i-1]>=s;i++){er[i]=lower_bound(a+i+1,a+n+1,a[i]+s)-(a+i/*-1*/);} cout << *min_element(er+1,er+n+1) << endl;}return 0 ; }?
尺取法:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <queue> #include <algorithm> using namespace std;int t; int n,S; int a[100005]; int sum[100005];int main(){cin >> t;while (t--){cin >> n >> S;for (int i=0;i<n;i++){cin >> a[i];}int ans=n+1;int s=0,t=0,sum=0;while (1){while (t<n&&sum<S){sum+=a[t++];}if (sum<S) break;ans=min(ans,t-s);sum-=a[s++];}if (ans>n) ans=0;cout << ans << endl;}}?
總結
以上是生活随笔為你收集整理的*【POJ - 3061】 Subsequence (尺取或二分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: msstat.exe - msstat是
- 下一篇: mssvr.exe - mssvr是什么