Educational Codeforces Round 33 D. Credit Card
Credit Card
time limit per test2 seconds
memory limit per test256 megabytes
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.
She starts with 0 money on her account.
In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.
In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.
It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».
Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
Input
The first line contains two integers n, d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) —the number of days and the money limitation.
The second line contains n integer numbers a1, a2, ... an ( - 104 ≤ ai ≤ 104), where ai represents the transaction in i-th day.
Output
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
Examples
inputCopy
5 10
-1 5 0 -5 3
outputCopy
0
inputCopy
3 4
-10 0 20
outputCopy
-1
inputCopy
5 10
-5 0 10 -11 0
outputCopy
2
找了一个写的比较好的中文题面QAQ。。。
有一张信用卡可以使用,每天白天都可以去给卡充钱。到了晚上,进入银行对卡的操作时间,操作有三种:
1.ai>0 银行会给卡充入ai元
2.ai<0 银行从卡中扣除ai元
3.ai=0 银行对你的卡进行评估,违背了规则就无权再使用此卡
规则1:卡内的余额不得超过d元
规则2:当ai=0时,卡内的余额不能是负数
现在问为了维持信用的平衡,最少去银行几次。(去一次,充一次钱)
反正看各种大神的算法感觉特别厉害。。。
我自己yy了一个乱七八糟的东西,运气好就1A了233
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, d, ans, a[maxn], b[maxn], c[maxn];
vector<int> lpl;
inline void check()
{
for(int i = 1; i <= n; ++i) printf("%d ", a[i]); printf("\n");
for(int i = 1; i <= n; ++i) printf("%d ", b[i]); printf("\n");
for(int i = 1; i <= n; ++i) printf("%d ", c[i]); printf("\n");
}
inline void prework()
{
int sum = 0;
for(int i = 1; i <= n; ++i){
if(a[i] == 0){
lpl.push_back(i);
if(sum < 0){b[i] = -sum; sum = 0;}
c[i] = sum;
continue;
}
sum += a[i]; if(sum > d){printf("-1"); exit(0);}
}
//check();
}
inline void workk()
{
ans = lpl.size();
for(int i = lpl.size() - 1; i >= 1; --i){
int now = lpl[i], pre = lpl[i - 1], sum = c[pre], mx = sum;
for(int j = pre + 1; j < now; ++j)
{sum += a[j]; mx = max(mx, sum);}
if(mx + b[now] <= d){ans--; b[pre] += b[now];}
}
if(b[1] == 0) ans--; cout << ans;
}
int main()
{
scanf("%d%d", &n, &d); n++; a[1] = 0;
for(int i = 2; i <= n; ++i) scanf("%d", &a[i]);
prework(); workk();
return 0;
}