HDU - 6444 Neko's loop(单调队列,思维)

Neko has a loop of size nn. 
The loop has a happy value aiai on the i−th(0≤i≤n−1)i−th(0≤i≤n−1) grid. 
Neko likes to jump on the loop.She can start at anywhere. If she stands at i−thi−thgrid, she will get aiai happy value, and she can spend one unit energy to go to ((i+k)modn)−th((i+k)modn)−th grid. If she has already visited this grid, she can get happy value again. Neko can choose jump to next grid if she has energy or end at anywhere.
Neko has mm unit energies and she wants to achieve at least ss happy value. 
How much happy value does she need at least before she jumps so that she can get at least ss happy value? Please note that the happy value which neko has is a non-negative number initially, but it can become negative number when jumping.

Input

The first line contains only one integer T(T≤50)T(T≤50), which indicates the number of test cases. 
For each test case, the first line contains four integers n,s,m,k(1≤n≤104,1≤s≤1018,1≤m≤109,1≤k≤n)n,s,m,k(1≤n≤104,1≤s≤1018,1≤m≤109,1≤k≤n). 
The next line contains nn integers, the i−thi−th integer is ai−1(−109≤ai−1≤109)ai−1(−109≤ai−1≤109) 

Output

For each test case, output one line "Case #x: y", where x is the case number (starting from 1) and y is the answer.

Sample Input

2
3 10 5 2
3 2 1
5 20 6 3
2 3 2 1 5

Sample Output

Case #1: 0
Case #2: 2

 

 

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define ll long long
const int maxn = 4 * 10005;
//	a1 + s = b1 * n + e
//	a2 + s = b2 * n + e
int n, m, k, s, cnt;
ll sum[maxn], a[maxn], b[maxn];
deque<int>q;
bool vis[maxn];
ll dp(int len, int cnt) {
	q.clear();
	ll ans = 0;
	for (int i = 1; i <= cnt; i++) {
		sum[i] = sum[i - 1] + b[i];
	}
	for (int i = 1; i <= cnt; i++) {
		while (q.size() && sum[q.front()] > sum[i]) {
			q.pop_front();
		}
		q.push_front(i);
		while (q.size() && i - len > q.back()) {
			q.pop_back();
		}
		if (i > 1)ans = max(ans, sum[i] - sum[q.back()]);
		else ans = max(ans, sum[i]);
	}
	return ans;
}
int main() {
	ios::sync_with_stdio(0);
	int te; cin >> te;
	for (int cas = 1; cas <= te; cas++) {
		cin >> n >> s >> m >> k;
		ll ans = 0;
		memset(vis, 0, sizeof(vis));
		for (int i = 0; i < n; i++)
			cin >> a[i];
		for (int i = 0; i < n; i++) {
			ll tmp = 0, su = 0; cnt = 0; int j = i;
			if (vis[i])continue;
			while (!vis[j]) {
				vis[j] = 1;
				b[++cnt] = a[j]; su += a[j];
				j = (j + k) % n;
			}
			for (int j = 1; j <= cnt; j++) {
				b[cnt + j] = b[j];
			}
			tmp = max(tmp, dp(cnt, cnt * 2));
			if (su > 0) {
				tmp = max(tmp + su*(m / cnt - 1), dp(m%cnt, cnt * 2) + (m / cnt)*su);
			}
			ans = max(ans, tmp);
		}
		cout << "Case #" << cas << ":" << " " << max(0ll, s - ans) << endl;
	}
}

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务