Hoj 2143 Songs

本文解析了一道关于歌曲播放顺序优化的ACM编程题。通过数学推导得出按歌曲长度与频率比升序排列可得最小总代价的结论,并提供了一个使用C++实现的排序解决方案。

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

题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=2143

若有两相邻的song,准备先听的那个时间为L1,听的频率为F1,后听的那个分别为L2和F2 

设他们前面的所有歌的长度和为S。 

他们两个产生的代价为 S * F1 + ( S + L1 ) * F2 = S * ( F1 + F2 ) + L1 * F2 

若交换,那么新代价为 S * F2 + ( S + L2 ) * F1 = S * ( F1 + F2 ) + L2 * F1 

那么显然,L1 * F2 <= L2 * F1 ( 因为我们假设这个排列已经最优 ) 

两边都除以 F1 * F2 ,那么有 L1 / F1 <= L2 / F2 

对任意的相邻的song都有这个性质,那么对整个排列方案而言,那么整个排列都是按 Li / Fi 升序排列的。

#include <iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;

struct Song
{
    int num;
    double len;
    double f;
};
Song so[100000];

bool cmp(Song a,Song b)
{
    return a.len * b.f <b.len * a.f;
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int n;
    int r;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
        {
            scanf(" %d %lf %lf",&so[i].num,&so[i].len,&so[i].f);
        }
        scanf(" %d",&r);
        sort(so,so+n,cmp);
        printf("%d\n",so[r-1].num);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值