【POJ】[3061] Subsequence

Problem Description

Loading...

Problem Analysis

At first I thought about sorting and taking from largest to smallest
But I overlooked the meaning of “subsequence” — the order cannot be changed
For example
1
5 10
1 1 5 1 5
this case
should output 3 rather than 2

So this binary search is very handy

Binary search here means searching the array for the position of the value greater than or equal to a certain value
i.e. the principle of lower_bound()
This time I didn’t call it
I tried writing it myself
After many revisions and much understanding
I finally got a satisfying result

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<stdio.h>
#include<algorithm>
using namespace std;
int sum[100200];
int n,m;
int find(int x) {
	int lt=x,rt=n,mid;
	while(rt-lt>0) {
		mid=(lt+rt)/2;
		if(sum[mid]-sum[x-1]<m) {
			lt=mid+1;
		} else {
			rt=mid;
		}
	}
	return lt;
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		scanf("%d %d",&n,&m);
		sum[0]=0;
		for(int i=1; i<=n; i++) {
			int t;
			scanf("%d",&t);
			sum[i]=sum[i-1]+t;
		}
		if(sum[n]<m) {
			printf("0\n");
			continue;
		}
		int res=9999999;
		for(int i=1; sum[i-1]+m<=sum[n]; i++) {
			int t=find(i)-i+1;
			res=min(res,t);
		}
		printf("%d\n",res);
	}
	return 0;
}

20160430 addendum:
A month’s progress is quite something
Binary search the answer
AC on the first try

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<stdio.h>
int a[100200];
int sum[100200];
int n,s;
bool judge(int m) {
	for(int i=1; i<=n-m+1; i++) {
		if(sum[i+m-1]-sum[i-1]>=s)
			return true;
	}
	return false;
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		scanf("%d %d",&n,&s);
		sum[0]=0;
		for(int i=1; i<=n; i++) {
			scanf("%d",&a[i]);
			sum[i]=sum[i-1]+a[i];
		}
		if(!judge(n)) {
			printf("0\n");
			continue;
		}
		int l=1,r=n;
		int res;
		while(r>=l) {
			int mid=(l+r)/2;
			if(judge(mid)) {
				res=mid;
				r=mid-1;
			} else
				l=mid+1;
		}
		printf("%d\n",res);
	}
	return 0;
}

Problem link:POJ 3061 Subsequence

Reference article:[ACM] POJ 3061 Subsequence (two-pointer method)

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...