UVA 1121 - Subsequence(贪心+优先队列 or TwoPointer)

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 

Many test cases will be given. 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 there isn‘t such a subsequence, print 0 on a line by itself.

Sample Input 

10 15 
5 1 3 5 10 7 4 9 2 8 
5 11 
1 2 3 4 5

Sample Output 

2 
3

题意:给定一个长度n的序列,和s,求一个最短子序列和不小于s。

思路:1、先求出所有位置的前缀和。然后利用优先队列优化,队头为和最小的,然后遍历一遍,遍历过程中如果满足情况就保留ans并出队。

    2、用two pointer的思想,因为数字都是正数,要吗增要码减,用h、r两个下标,维护r - h最短即可。

代码:

优先队列版:

#include <stdio.h>
#include <string.h>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

const int N = 100005;
int max(int a, int b) {return a>b?a:b;}
int min(int a, int b) {return a<b?a:b;}

int n, s, num;
struct Sum {
	int s, id;
	friend bool operator < (Sum a, Sum b) {
		return a.s > b.s;
	}
} sum[N];

void init() {
	for (int i = 1; i <= n; i++) {
		scanf("%d", &num);
		sum[i].s = sum[i - 1].s + num;
		sum[i].id = i;
	}
}

int solve() {
	int ans = INF;
	priority_queue<Sum>Q;
	sum[0].s = 0; sum[0].id = 0; Q.push(sum[0]);
	for (int i = 1; i <= n; i++) {
		while(!Q.empty() && sum[i].s - Q.top().s >= s) {
			ans = min(ans, sum[i].id - Q.top().id);
			Q.pop();
		}
		Q.push(sum[i]);
	}
	if (ans == INF) return 0;
	return ans;
}

int main() {
	while (~scanf("%d%d", &n, &s)) {
		init();
		printf("%d\n", solve());
	}
	return 0;
}

two pointer版:

#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
void scanf_(int &num)
{
    char in;
    bool neg=false;
    while(((in=getchar()) > ‘9‘ || in<‘0‘) && in!=‘-‘) ;
    if(in==‘-‘)
    {
        neg=true;
        while((in=getchar()) >‘9‘ || in<‘0‘);
    }
    num=in-‘0‘;
    while(in=getchar(),in>=‘0‘&&in<=‘9‘)
        num*=10,num+=in-‘0‘;
    if(neg)
        num=0-num;
}
const int N = 100005;
int max(int a, int b) {return a>b?a:b;}
int min(int a, int b) {return a<b?a:b;}

int n, s, num[N];

void init() {
	for (int i = 0; i < n; i++)
		scanf_(num[i]);
}

int solve() {
	int ans = INF, sum = 0;
	int h = 0, r = 0;
	while (r < n) {
		sum += num[r++];
		while (sum - num[h] >= s) {sum -= num[h++];}
		if (sum >= s) ans = min(ans, r - h);
	}
	if (ans == INF) return 0;
	return ans;
}

int main() {
	while (~scanf("%d%d", &n, &s)) {
		init();
		printf("%d\n", solve());
	}
	return 0;
}


UVA 1121 - Subsequence(贪心+优先队列 or TwoPointer)

上一篇:FusionCharts 2D柱状图和折线图的组合图


下一篇:OLAT使用问题