[codeforces1203F1]Complete the Projects (easy version) (貪心)

題目

[codeforces1203F1]Complete the Projects (easy version)

題意

有一些任務要做,做任務有前提,就是你的rating要大於等於這個任務要求的rating,而做了這個任務後,你的rating會變化bi,bi可正可負。問能否完成給定的所有任務呢?

思路

分兩種情況討論,一種是bi大於等於0的,對於這種我們優先完成ai小的,也就是優先完成rating要求小的任務,維護r值,每次做任務都判斷 r 值是否大於rating的要求。

然後再來看bi小於 0 的,對於這些任務,我們按它的ai + bi的值從大到小的順序來完成任務,每次做任務都看r是否大於rating。

最後再判斷一下r是否大於等於0即可。

代碼寫的比較冗餘,可以優化。

代碼

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e2 + 5;
const ll mod = 1e9 + 7;
struct node{
    int a, b;
}p[maxn], new_p[maxn];

bool cmp1(node a, node b){
    return a.b > b.b;
}

bool cmp2(node a, node b){
    return a.a < b.a;
}

bool cmp3(node a, node b){
    return a.a + a.b > b.a + b.b;
}

int main()
{
    int n, r;
    scanf("%d %d", &n, &r);
    for(int i = 1; i <= n; i++)
    {
        scanf("%d %d", &p[i].a, &p[i].b);
    }
    sort(p + 1, p + 1 + n, cmp1);
    int pos = 1;
    while(pos <= n && p[pos].b >= 0){
        pos++;
    }
    pos--;
    sort(p + 1, p + 1 + pos, cmp2);

    for(int i = 1; i <= pos; i++)
    {
        if(p[i].a > r)
            return 0 * printf("NO\n");
        r += p[i].b;
    }

    sort(p + 1 + pos, p + 1 + n, cmp3);

    int cnt = 0;
    for(int i = pos + 1; i <= n; i++)
    {
        cnt++;
        new_p[cnt] = p[i];
    }

    for(int i = 1; i <= n; i++)
    {
        if(r >= new_p[i].a)
            r += new_p[i].b;
        else
            return 0 * printf("NO\n");
    }
    if(r >= 0)
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}
/*
5 5
5 2
6 3
8 -3
7 -2
5 -1

5 5
5 2
6 3
8 -3
7 -2
6 -1

5 5
5 2
6 3
8 -3
7 -2
5 -5

5 5
5 2
6 3
8 -3
7 -2
5 -6

2 5
4 -100
2 -50
*/
發佈了184 篇原創文章 · 獲贊 24 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章