纪念品分组

瘦欲@ 提交于 2020-01-31 13:34:48

传送门

题意:
把n个纪念品分组,每组的价格之和<=w,并且每组最多两个纪念品

排序,i从最小的开始,j从最大的开始,符合题意,标记,j–;
不符合的话,j单独一组,j–;直到符合题意的出现

#include <bits/stdc++.h>
using namespace std;
int n,p[30010],w,vis[30010];
int cnt;
int main(){
    //freopen("in","r",stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> w >> n;
    int i;
    for(i = 0; i < n; i++)
        cin >> p[i];
    sort(p,p+n);
    i = n - 1;
    for(int j = 0; j < n; j++){
        if(vis[j] && vis[i])
            break;
        if(vis[i] || vis[j]){
            cnt++;
            break;
        }
        if(p[j] + p[i] <= w){
            vis[i] = vis[j] = 1;
            cnt++;
            i--;
        }else {
            while (p[j] + p[i] > w) {
                vis[i] = 1;
                cnt++;
                i--;
            }
            vis[i] = vis[j] = 1;
            cnt++;
            i--;
        }
    }
    cout << cnt << endl;
    return 0;
}

其他贪心

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!