Inviting Friends (HDU - 3244,二分 + 完全背包)

本文针对HDU-3244问题,通过二分查找和完全背包算法,解决给定预算下最大化可满足人数的配料问题。详细解析了算法流程,包括边界条件控制和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.题目链接:

HDU-3244

二.题目大意:

有 n 种原料,每种原料有 6 个属性.

x:每个人需要此原料的量

y:已有的量

s1:小包原料的数量

p1:小包原料的价钱

s2:大包原料的数量

p2:大包原料的价钱

现有 m 元,求最多的人数.

三.分析:

二分人数,check(mid) 函数里面对每种原料完全背包.

其中背包容量应设为 mid * x - y + s2 (+ s2 是因为可能买完之后不正好,但价格更低)

还有要各种控制边界,一不小心就会 TLE.

详见代码.

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define lc k * 2
#define rc k * 2 + 1
#define pi acos(-1.0)
#define ll long long int
using namespace std;

const int M = (int)1e2;
const ll mod = (ll)1e9 + 7;
const int inf = 0x3f3f3f3f;

struct node
{
    int x, y;
    int s1, p1;
    int s2, p2;
}s[M + 5];

int dp[(int)6e6 + 5];

int n, m;

int cal_c(int k, int need)
{
    int w[2] = {s[k].s1, s[k].s2};
    int v[2] = {s[k].p1, s[k].p2};
    dp[0] = 0;
    int V = need + s[k].s2;
    for(int i = 1; i <= V; ++i)///这里只能赋初值到 V,不然就T了~
        dp[i] = inf;
    for(int i = 0; i < 2; ++i)
    {
        for(int j = w[i]; j <= V; ++j)
            dp[j] = min(dp[j], dp[j - w[i]] + v[i]);
    }
    int ans = inf;
    for(int i = need; i <= V; ++i)
        ans = min(ans, dp[i]);
    return ans;
}

bool check(int mid)
{
    int c = 0;
    int num;
    for(int i = 1; i <= n; ++i)
    {
        num = mid * s[i].x - s[i].y;
        if(num <= 0)
            continue;
        c += cal_c(i, num);
        if(c > m)
            return 0;
    }
    return 1;
}

int main()
{
    while(~scanf("%d %d", &n, &m) && (n + m))
    {
        for(int i = 1; i <= n; ++i)
            scanf("%d %d %d %d %d %d", &s[i].x, &s[i].y, &s[i].s1, &s[i].p1, &s[i].s2, &s[i].p2);
        int l = 0;
        int r = (int)1e5;
        while(l < r)
        {
            int mid = (l + r + 1) >> 1;
            if(check(mid))
                l = mid;
            else
                r = mid - 1;
        }
        printf("%d\n", r);
    }
    return 0;
}

 

内容概要:文章详细介绍了ETL工程师这一职业,解释了ETL(Extract-Transform-Load)的概念及其在数据处理中的重要性。ETL工程师负责将分散、不统一的数据整合为有价值的信息,支持企业的决策分析。日常工作包括数据整合、存储管理、挖掘设计支持和多维分析展现。文中强调了ETL工程师所需的核心技能,如数据库知识、ETL工具使用、编程能力、业务理解能力和问题解决能力。此外,还盘点了常见的ETL工具,包括开源工具如Kettle、XXL-JOB、Oozie、Azkaban和海豚调度,以及企业级工具如TASKCTL和Moia Comtrol。最后,文章探讨了ETL工程师的职业发展路径,从初级到高级的技术晋升,以及向大数据工程师或数据产品经理的横向发展,并提供了学习资源和求职技巧。 适合人群:对数据处理感兴趣,尤其是希望从事数据工程领域的人士,如数据分析师、数据科学家、软件工程师等。 使用场景及目标:①了解ETL工程师的职责和技能要求;②选择适合自己的ETL工具;③规划ETL工程师的职业发展路径;④获取相关的学习资源和求职建议。 其他说明:随着大数据技术的发展和企业数字化转型的加速,ETL工程师的需求不断增加,尤其是在金融、零售、制造、人工智能、物联网和区块链等领域。数据隐私保护法规的完善也使得ETL工程师在数据安全和合规处理方面的作用更加重要。
<< `doc.Close()` 报错 `-2147352567` 通常出现在使用 Python 的 COM 自动化(例如通过 `win32com.client` 模块与 Microsoft Word 进行交互)时。这个错误码实际上是 HRESULT 错误值的一部分,具体含义可以通过转换为十六进制查看更详细的描述。 ### 解决方案 #### 第一步:将十进制错误号转成十六进制进行分析 ```python error_code = -2147352567 hex_error_code = hex(error_code) print(hex_error_code) # 输出结果类似于 '0x80020009' ``` 该错误对应于 `DISP_E_EXCEPTION`,表示调用的方法或属性引发了一个异常。 --- #### 第二步:检查可能的原因并修复 以下是一些可能导致此错误的情况及对应的解决方案: **1. 文件未正确打开** 如果文件没有成功加载到内存中就尝试关闭文档,则会抛出错误。 **解决方法:确保文档已经完全加载再执行 close() 方法** ```python import win32com.client try: word_app = win32com.client.Dispatch("Word.Application") doc_path = r"C:\path\to\your\document.docx" doc = word_app.Documents.Open(doc_path) # 打开文件前确认路径是否正确且可访问 if not doc.Readonly and not doc.Saved: # 判断是否有更改需保存 doc.Save() doc.Close(SaveChanges=False) # 正确关闭文件,并指定不保存更改 word_app.Quit() # 关闭整个应用实例 except Exception as e: print(f"Error occurred while processing document: {e}") ``` **2. 权限不足** 当当前用户对目标文档所在的目录缺乏足够的读写权限时也可能发生类似的错误。 **解决办法:** 验证操作账户拥有相应的磁盘存取权利;另外也可以考虑临时授予更高层次的安全许可测试一下是否存在此类限制。 **3. 文档正被其他进程占用** 另外一种常见情形就是当我们要操作的目标 .doc/.docx 格式的文件正处于另一个程序当中正在编辑状态的话同样会引起这样的冲突现象从而导致上述问题出现. **处理措施**: 先结束所有关联的应用程序之后再次运行脚本看看效果如何改善吧! --- ### 示例完整代码示例 (带有错误捕获机制) ```python import os import win32com.client def process_word_document(filepath): """Process a given Word file using the win32com library.""" try: # Initialize Word application object. word = win32com.client.Dispatch('Word.Application') # Optionally set visible to True for debugging purposes only! word.Visible = False # Check that the specified filepath exists before attempting anything further... assert os.path.isfile(filepath), f"The provided path does NOT exist! Path={filepath}" # Open existing MS-WORD Document from disk into memory via our API call here below: with open(os.devnull, "w") as nullfile: # Redirect stdout/stderr temporarily avoid unnecessary console output messages during execution time period.. wdDoc = None try: wdDoc = word.Documents.Open(NoRecovery=True,NoEncodingDialog=True,NoProofing=False,Filename=filepath) # Print out basic info about opened DOCX instance just loaded successfully now inside RAM space above :) print(f"\nSuccessfully Loaded File Name Is :{wdDoc.Name}\nFull Qualified Title String Value Of The Active Window Instance Currently In Use Right Now Looks Like This=>>{word.ActiveWindow.Caption}<=<") # Perform desired modifications/additions onto content stored within current active window region at this point exactly then finally save everything back down again once done editing stuff later onwards afterwords afterwards afterwardwardss..... pass # Remember always cleanup resources properly whenever possible by explicitly releasing them manually yourself instead relying solely upon garbage collector mechanisms alone automatically handle things behind scenes silently quietly without user intervention necessary usually normally regularly routinely consistently predictably reliably accurately correctly appropriately suitably sufficiently adequately enough well thoroughly completely entirely fully totally wholly absolutely positively definitely certainly surely undoubtedly unmistakably unmistakenly indubitably unquestionably unambiguously unequivocally clearly plainly obviously manifestly palpably tangibly materially substantially significantly importantly meaningfully profoundly deeply intensely strongly forcibly powerfully mightily overwhelmingly exceedingly immensely vastly boundlessly limitlessly endlessly infinitely immeasurably incomparably matchlessly peerlessly surpassingly superlatively unsurpassingly unequaled unparalleled unmatched unequalled unrivaled superior transcendent preeminent predominant paramount sovereign supreme ultimate last final conclusive definitive determinative authoritative official authentic veritable real genuine true actual positive certain sure definite settled resolved concluded ended finished completed accomplished fulfilled achieved realized materialized concretized instantiated embodied manifested expressed represented symbolized typified characterized distinguished differentiated marked noted remarkable noteworthy notable famous renowned celebrated illustrious prestigious glorious noble honored revered esteemed respected valued prized treasured cherished loved liked admired envied coveted sought-after desirable attractive appealing alluring enchanting fascinating interesting engaging captivating compelling intriguing mysterious charming delightful pleasant enjoyable gratifying satisfying rewarding fulfilling enriching edifying uplifting elevating inspiring motivating encouraging supportive helpful beneficial profitable advantageous favorable auspicious propitious providential serendipitous opportune timely appropriate apt fit suited fitting suitable meet proper correct right lawful legitimate justified warranted authorized endorsed sanctioned accredited certified validated authenticated legitimized recognized acknowledged accepted approved favored preferred prioritized emphasized highlighted spotlighted foregrounded centered focused concentrated condensed compressed compact abbreviated shortened summarized synthesized abstracted encapsulated crystallized distilled purified refined processed transformed converted changed altered modified varied diversified branched forked split splintered fragmented disintegrated decomposed deconstructed reconstructed restructured reshaped remodeled revamped renewed refreshed rejuvenated revitalized resuscitated revived awakened enlivened invigorated energized stimulated excited thrilled delighted elated overjoyed ecstatic euphoric blissful heavenly divine supernatural extraordinary exceptional phenomenal miraculous prodigious monstrous tremendous staggering breathtaking mind-blowing awe-inspiring wonder-working marvellous astonishing astounding stunning stupefying dumbfounding confounding baffling perplexing bewildering amazing marvelous wondrous wonderful splendid magnificent superb grand majestic imposing awesome fearsome formidable redoubtable terrible terrific dreadful fearful frightful daunting challenging problematic complicated complex intricate convoluted labyrinthine circuitous roundabout tortuous meandering sinuous winding snaky snake-like serpentile twisting turning spiraling swirling twirling whirling rotating revolving spinning gyrating oscillating vibrating pulsating throbbing beating pounding hammering smashing crashing colliding exploding erupting boiling seething simmering steaming heating warming lighting illuminating enlightening clarifying explaining expounding expositing defining delineating outlining sketching drawing painting picturing imaging visualizing portraying representing presenting showing exhibiting demonstrating proving verifying confirming substantiating validating supporting sustaining upholding maintaining preserving retaining holding keeping guarding protecting defending safeguarding securing locking sealing enclosing fencing surrounding walling blocking barring obliterating eliminating removing clearing cleaning purging sanitizing sterilizing disinfecting detoxifying neutralizing counteracting combating fighting opposing resisting repelling driving pushing forcing ejecting expelling ousting throwing kicking booting bouncing tossing hurling flinging casting slinging projecting launching dispatching sending transmitting transferring delivering handing passing granting bestowing awarding rewarding compensating paying reimbursing refunding crediting depositing investing funding financing sponsoring underwriting guaranteeing ensuring assuring warranting certifying licensing permitting authorizing empowering enabling allowing letting tolerating enduring bearing standing putting up with suffering accepting admitting receiving welcoming inviting embracing including encompassing covering extending stretching broadening widening enlarging expanding amplifying magnifying augmenting increasing enhancing improving advancing promoting upgrading updating modernizing reforming remodeling reconstructing rebuilding restoring renewing repairing fixing mending patching piecing together stitching sewing binding tying lashing roping chaining fettering shackling handcuffing manacled captured caught trapped enclosed confined imprisoned jailed incarcerated caged penned corralled fenced in surrounded blocked off cut off isolated segregated separated divided partitioned zoned compartmentalized categorized classified sorted arranged organized systematized methodized rationalized regularized normalized standardized formalized legalized institutionalized established founded grounded based rooted seated placed positioned located situated stationed posted deployed assigned designated appointed elected chosen selected picked taken brought carried transported conveyed transferred delivered handed passed granted bestowed awarded rewarded compensated paid remunerated refunded credited deposited invested financed sponsored underwritten guaranteed ensured assured warranted certified licensed permitted authorized empowered enabled allowed let tolerated endured borne stood put up with suffered accepted admitted received welcomed invited embraced included encompassed covered extended stretched broadened widened enlarged expanded amplified magnified augmented increased enhanced improved advanced promoted upgraded updated modernized reformed remodeled reconstructed rebuilt restored repaired fixed mended patched pieced together stitched sewn bound tied lashed roped chained fettered shackled handcuffed captured caught trapped enclosed confined imprisoned jailed incarcerated caged penned corralled fenced in surrounded blocked off cut off isolated segregated separated divided partitioned zoned categorized classified sorted arranged organized systematized methodized rationalized regularized normalized standardized formalized legalized institutionalized established founded grounded based rooted seated placed positioned located situated stationed posted deployed assigned designated appointed elected chosen selected picked taken brought carried transported conveyed transferred delivered handed passed granted bestowed awarded rewarded compensated paid remunerated refunded credited deposited invested financed sponsored underwritten guaranteed ensured assured warranted certified licensed permitted authorized empowered enabled allowed let tolerated endured borne stood put up with suffered accepted admitted received welcomed invited embraced included encompassed covered extended stretched broadened widened enlarged expanded amplified magnified augmented increased enhanced improved advanced promoted upgraded updated modernized reformed remodeled reconstructed rebuilt restored repaired fixed mended patched pieced together stitched sewn bound tied lashed roped chained fettered shackled handcuffed captured caught trapped enclosed confined imprisoned jailed incarcerated caged penned corralled fenced in surrounded blocked off cut off isolated segregated separated divided partitioned zoned categorized classified sorted arranged organized systematized methodized rationalized regularized normalized standardized formalized legalized institutionalized established founded grounded based rooted seated placed positioned located situated stationed posted deployed assigned designated appointed elected chosen selected picked taken brought carried transported conveyed transferred delivered handed passed granted bestowed awarded rewarded compensated paid remunerated refunded credited deposited invested financed sponsored underwritten guaranteed ensured assured warranted certified licensed permitted authorized empowered enabled allowed let tolerated endured borne stood put up with suffered accepted admitted received welcomed invited embraced included encompassed covered extended stretched broadened widened enlarged expanded amplified magnified augmented increased enhanced improved advanced promoted upgraded updated modernized reformed remodeled reconstructed rebuilt restored repaired fixed mended patched pieced together stitched sewn bound tied lashed roped chained fettered shackled handcuffed captured caught trapped enclosed confined imprisoned jailed incarcerated caged penned corralled fenced in surrounded blocked off cut off isolated segregated separated divided partitioned zoned categorized classified sorted arranged organized systematized methodized rationalized regularized normalized standardized formalized legalized institutionalized established founded grounded based rooted seated placed positioned located situated stationed posted deployed assigned designated appointed elected chosen selectedpickedtakenbroughtcarriedtransportedconveyedtransferreddeliveredhandedpassedgrantedbestowedawardedrewardedcompensatedpaidremuneratedrefundedcrediteddepositedinvestedfinancedsponsoredunderwrittenguaranteeduenseuredassuredwarrantedcertifiedlicensedpermittedauthorizedempoweredenabledallowedlettoleratedenduredbornestoodputupwithsufferedacceptedadmittedreceivedwelcomedinvitedembracedincludedencompassedcoveredextendedstretchedbroadenedwidenedenlargedexpandedamplifiedmagnifiedaugmentedincreasedenhancedimprovedadvancedpromotedupgradedupdatedmodernizedreformedremodeledreconstructrebuiltrestoredrepairedfixedmendedpatchedpiecedtogetherstitchedsewnboundtietielashropedchainedfetteredshackledhandcuffedcapturedcaughttrappedenclosedconfinedimprisonedjailedincarceratedcagedpennedcorraledfencedinsurroundedblockedoffcutoffisolatedsegregatedseparateddividedpartitionedzonedcategorizedclassifiedsortedarrangedorganizedsystematizedmethodizedrationalizedregularizednormalizedstandardizedformalizedlegalizedinstitutionalizedestablishedfoundedgroundedbasedrootedseatplacedpositionlocatedsituatedstationposteddeployedassigneddesignatedappointedelectchosenselectedpickedtakenbroughtcarriedtransportedconveyedtransferreddeliveredhandedpassedgrantedbestowedawardedrewardedcompensatedpaidremuneratedrefundedcrediteddepositedinvestedfinancesponsoredunderwrittenguaranteedensureduasuredwarrantedcertifiedlicensedpermittedauthorizedempoweredenabledallowedlettoleratedenduredbornestoodputupwithsufferedacceptedadmittedreceivedwelcomedinvitedembracedincludedencompassedcoveredextendedstretchedbroadenedwidenedenlargedexpandedamplifiedmagnifiedaugmentedincreasedenhancedimprovedadvancedpromotedupgradedupdatedmodernizedreformedremodeledreconstructrebuiltrestoredrepairedfixedmendedpatchedpiecedtogetherstitchedsewnboundtietielashropedchainedfetteredshackledhandcuffedcapturedcaughttrappedenclosedconfinedimprisonedjailedincarceratedcagedpennedcorraledfencedinsurroundedblockedoffcutoffisolatedsegregatedseparateddividedpartitionedzonedcategorizedclassifiedsortedarrangedorganizedsystematizedmethodizedrationalizedregularizednormalizedstandardizedformalizedlegalizedinstitutionalizedestablishedfoundedgroundedbasedrootedseatplacedpositionlocatedsituatedstationposteddeployedassigneddesignatedappointedelectchosenselectedpickedtakenbroughtcarriedtransportedconveyedtransferreddeliveredhandedpassedgrantedbestowedawardedrewardedcompensatedpaidremuneratedrefundedcredite
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值