浏览器标题切换
浏览器标题切换end

CodeForces1405B - Array Cancellation - 中等贪心

题意

给一个数组,每次可以任选一个进行操作:
操作一:选下标为\(i\)\(j\)\(i<j\)时,让\(a_{i}--\)\(a_{j}++\),花费硬币为0;
操作二:选下标\(i>j\)时,让\(a_{i}--\)\(a_{j}++\),花费硬币为1;
要求所有元素都为0,输出消耗最少的硬币数。

PS

过第三组数据的时候,VJ显示TLE,CF显示out of bounds

思路

我觉得是难的贪心耶,因为我么有写出来。
1、把花费为0的机会先用掉:遍历一遍,如果找到的元素大于0则以该数再开一个for循环往后遍历,判断后面的数字和该数的关系(绝对值大于还是小于)
2、再遍历一遍全部数组,大于0的元素累加即答案。

官方题解

很短 短小精悍 我都学不会这种短短的代码 又是写不出来的一天

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define sc(T) scanf("%d",&T)
#define scc(x,y) scanf("%d %d",&x,&y)
#define pr(T) printf("%d\n",T)
#define inf 0x3f3f3f3f

int main()
{
    // cout<<0LL<<endl; 0
    int T;
    sc(T);
    while(T--)
    {
        int n;
        sc(n);
        ll w=0;
        for(int i=0;i<n;i++)
        {
            ll x;
            cin>>x;
            w=max(0LL,w+x);
        }
        cout<<w<<endl;
    }
    return 0;
}

我的AC代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define sc(T) scanf("%d",&T)
#define scc(x,y) scanf("%d %d",&x,&y)
#define pr(T) printf("%d\n",T)
#define inf 0x3f3f3f3f

ll a[100020];

int main()
{
    int T;
    sc(T);
    while(T--)
    {
        int n;
        sc(n);
        for(int i=0; i<n; i++)
            scanf("%lld",&a[i]);
        for(int i=0; i<n; i++)
        {
            if(a[i]>0)
            {
                for(int j=i+1; j<n; j++)
                {
                    //if(a[j]<0)
                    ll w=abs(a[j]);
                    if(w>a[i])
                    {
                        a[j]+=a[i],a[i]=0; //先加再变0
                        break;
                    }
                    else
                        a[i]+=a[j],a[j]=0;
                }
            }
        }
        ll ans=0;
        for(int i=0; i<n; i++)
        {
            if(a[i]>0)
                ans+=a[i];
        }
        printf("%lld\n",ans);

    }
    return 0;
}
posted @ 2020-09-07 23:34  抓水母的派大星  阅读(221)  评论(0编辑  收藏  举报