Subsequence ZOJ:3123

博客围绕一个算法问题展开,给定N个正整数序列和正整数S,需用C++编写程序找出连续元素子序列的最小长度,使其和大于或等于S。还给出了输入输出格式及样例。

Subsequence


Time Limit: 1 Second      Memory Limit: 32768 KB


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 5

Sample Output

2
3
#include<bits/stdc++.h>
using namespace std;
int main() {
	int m;
	cin >> m;
	while (m--) {
		int n, s, sum(0), min(0);
		queue<int>q;
		cin >> n >> s;
		for (size_t i = 0; i < n; i++)
		{
			int temp;
			cin >> temp;
			sum += temp;
			q.push(temp);
			while (sum - q.front() > s)
			{
				sum -= q.front();
				q.pop();
			}
			if (sum >= s && (min > q.size() || min == 0)) {
				min = q.size();
			}
		}
		cout << min << endl;
	}
	//system("pause");
	return 0;
}

 

代码中素数生成时间为2468毫秒,后续计算时间为0毫秒,这种情况是有可能合理的。 素数生成是一个相对复杂且耗时的过程。生成1024位的素数,需要进行大量的随机数生成和素性测试。素性测试通常会采用一些概率性的算法,如米勒 - 罗宾素性测试,为了保证生成的数大概率是素数,需要进行多次测试,这会消耗较多的时间。所以,素数生成时间达到2468毫秒是合理的。 而后续计算部分,如计算`N = p * q`、`phi_N = (p - 1) * (q - 1)`、检查`gcd(e, phi_N) == 1`以及计算`e`的模逆元`d`,这些操作对于现代计算机的CPU来说,是相对简单的数学运算。这些运算的时间复杂度较低,在毫秒级别的时间测量精度下,可能会因为计算速度极快而导致测量结果显示为0毫秒。这是因为计算机执行这些运算的速度非常快,小于测量精度的最小单位。 ### 示例代码 ```cpp #include <NTL/ZZ.h> #include <NTL/ZZ_p.h> #include <iostream> #include <chrono> using namespace NTL; using namespace std; using namespace std::chrono; int main() { auto start1 = high_resolution_clock::now(); ZZ p, q; GenPrime(p, 1024); GenPrime(q, 1024); auto stop1 = high_resolution_clock::now(); auto duration1 = duration_cast<milliseconds>(stop1 - start1); cout << "Time taken for prime generation: " << duration1.count() << " milliseconds" << endl; auto start2 = high_resolution_clock::now(); ZZ N = p * q; ZZ phi_N = (p - 1) * (q - 1); ZZ e = to_ZZ(65537); ZZ gcd_result; GCD(gcd_result, e, phi_N); ZZ d; if (gcd_result == 1) { InvMod(d, e, phi_N); } auto stop2 = high_resolution_clock::now(); auto duration2 = duration_cast<milliseconds>(stop2 - start2); cout << "Time taken for subsequent calculations: " << duration2.count() << " milliseconds" << endl; return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值