2 solutions

  • 1
    @ 2023-8-15 15:45:55

    代码1(先看这个,再看2):

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    
    int main(){
        int n;
        vector<LL> a;
        cin>>n;
        for(int i=1;i<=n;i++){
            LL c;
            cin>>c;
            a.push_back(c);
        }
        LL sum=0;
        //先从大到小删除负数
        for(int i=n-1;i>=0;i--){
            if(a[i]<0){
                sum += a[i]*(i+1);
                a.erase(a.begin()+i);
            }
        }
        //再从小到大删除正数
        for(int i=0;i<a.size();){
            sum += a[i]*1;
            a.erase(a.begin()+i);
        }
        cout<<sum;
        return 0;
    }
    

    代码2: (此代码一气呵成,考虑到删除的元素,若是负数,权重为本身下标;若是正数,权重为1,即从第一个元素开始。建议先看代码1,理解过程。)

    #include<iostream>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    int n, m, i;
    ll ans;
    int main()
    {
        cin >> n;
        for(i=1; i<=n; i++)
        {
            cin >> m;
            if(m < 0)
                ans += (ll)m*i;
            else
                ans += m;
        }
        cout << ans << endl;
        return 0;
    }
    

    Information

    ID
    267
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    3
    Tags
    # Submissions
    511
    Accepted
    124
    Uploaded By