(贪心)【CF 893D】Credit Card

题目链接:D. Credit Card

题意大概就是一张信用卡,输入的数字是每天晚上对卡的操作,正数为存入钱,负数为消费(可透支),0为还款日还款。
题目要求有两个,一是任何时候卡内余额都不能超过d,否则直接输出-1,二是还款日的时候金额不能为负,所以还款日那天卡内余额是负的早上就要去存钱了。求最少的存钱次数。

因为当前存钱金额和后面的操作有关,在不超过d的情况下多存一点,后面也许就可以少去存一次钱,所以用一个变量delta记录之前的最高余额,当还款日时欠的钱加上delta<=d时,就意味着可以在之前的存钱操作中多存一点来满足还款日金额,就减少存钱次数了。

/*
http://codeforces.com/contest/893/problem/D
*/

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define LL long long
using namespace std;
inline LL read();
const int MAXN = 150+10;


int main(void)
{
    LL n = read(),d = read(),tmp,balance = 0,delta = d,ans = 0;
    for(int i = 1; i <= n; ++i)
    {
        tmp = read();
        if(tmp)
        {
            balance += tmp;
            if(balance > d)
            {
                printf("-1\n");
                exit(0);
            }
            delta = max(delta,balance);
        }
        else
        {
            if(balance < 0)
            {
                if(delta-balance <= d)
                    delta -= balance;
                else
                {
                    ++ans;
                    delta = 0;
                }
                balance = 0;
            }
        }
    }
    printf("%I64d\n",ans);
}

inline LL read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}


猜你喜欢

转载自blog.csdn.net/suiguia/article/details/78633088