3 条题解

  • 1
    @ 2025-7-25 20:25:38
    解决思路
    ‌问题分析‌:Marry乳业需要采购一定数量的牛奶,每个奶农提供的牛奶单价和产量不同。目标是在满足需求量的前提下,使总花费最小。
    ‌关键直觉‌:由于可以独立选择每个奶农的牛奶数量,且总产量大于需求量,最优策略是优先采购单价最低的牛奶。
    ‌算法选择‌:使用贪心算法:
    将所有奶农按牛奶单价从小到大排序。
    从单价最低的奶农开始采购,尽可能多地购买其牛奶,直到满足总需求量。
    如果当前奶农的产量大于剩余需求量,则只购买剩余需求量的牛奶。
    ‌复杂度分析‌:
    排序:O(M log M),其中 M 是奶农数量(最多5000),高效可行。
    遍历采购:O(M),同样高效。
    
    
    #include<queue>
    #include<math.h>
    #include<stdio.h>
    #include<iostream>
    #include<vector>
    #include<iomanip>
    #include<string.h>
    #include<algorithm>
    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<stack>
    #include <fstream>
    #include<string>
    using namespace std;
    #define LL long long
    const int N = 1e5 + 10;
    const int INF = 0x3f3f3f3f;
    struct Farmer
    {
        int price;
        int amount;
    };
    bool compare( Farmer a , Farmer b )
    {
        return a.price < b.price;
    }
    int main()
    {
        int n , m;
        cin >> n >> m;
        vector<Farmer> farmers(m);    
        for ( int i = 0 ; i < m ; ++i )
    	{
            cin >> farmers[i].price >> farmers[i].amount;
        }    
        sort( farmers.begin() , farmers.end() , compare );    
        int total = 0 , cost = 0;
        for ( int i = 0 ; i < m && total < n ; ++i )
    	{
            int buy = min( farmers[i].amount , n - total );
            cost += buy * farmers[i].price;
            total += buy;
        }    
        cout << cost << endl;
        return 0;
    }
    
    
    

    代码解释 ‌输入处理‌: 读取总需求量 N 和奶农数量 M。 使用vector<pair<int, int>>存储每个奶农的单价和产量。 ‌排序‌:使用sort函数将奶农按牛奶单价升序排列。 ‌贪心采购‌: 初始化totalCost(总花费)和remaining(剩余需求量)。 遍历排序后的奶农列表: 若当前奶农的产量 <= 剩余需求量,则全部采购。 否则,只采购剩余需求量的牛奶。 更新总花费和剩余需求量。 ‌输出结果‌:打印最小总花费。 此方案高效且正确,能够在O(M log M)时间内解决问题,适用于给定的数据范围。

    信息

    ID
    553
    时间
    1000ms
    内存
    256MiB
    难度
    9
    标签
    递交数
    147
    已通过
    14
    上传者