UVa 1346 Songs (貪心好題)

來源:互聯網
上載者:User

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=4092 思路:直接看這個和式,記A(i)=f(i)Σl(j) (1<=j<=i),則sum=ΣA(i)(別被下標迷惑了,s(i)完全可以用i代替)。

設sum已經達到最小,

記sum1 = A(i)+A(i+1) = (f(i)+f(i+1))*(l(1)+...+l(i-1)) + f(i)*l(i) + f(i+1)*l(i) + f(i+1)*l(i+1)

交換f(i)和f(i+1),交換l(i)和l(i+1),得sum2= (f(i)+f(i+1))*(l(1)+...+l(i-1)) + f(i)*l(i) + f(i)*l(i+1) + f(i+1)*l(i+1)

因為sum最小,必有sum1<=sum2,故f(i+1)*l(i)<=f(i)*l(i+1)

(也可以這麼理解,頻率越大的,長度越短的,即f(i)/l(i)越大的,位置越靠前)

完整代碼:

01./*0.032s*/02.  03.#include<bits/stdc++.h>  04.using namespace std;  05.  06.struct node  07.{  08.    int id;  09.    double l, f;  10.    bool operator < (const node& a) const11.    {  12.        return a.f * l < f * a.l;  13.    }  14.} a[65540];  15.  16.int main()  17.{  18.    int n, i, s;  19.    while (~scanf("%d", &n))  20.    {  21.        for (i = 1; i <= n; ++i)  22.            scanf("%d%lf%lf", &a[i].id, &a[i].l, &a[i].f);  23.        scanf("%d", &s);  24.        nth_element(a + 1, a + s, a + n + 1);  25.        printf("%d\n", a[s].id);  26.    }  27.    return 0;  28.}

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.