經典的貪心演算法 Journey with Pigs (POJ 3544)

來源:互聯網
上載者:User

Description

Farmer John has a pig farm near town A. He wants to visit his friend living in town B. During this journey he will visit n small villages so he decided to earn some money. He tooks n pigs and plans to sell one pig in each village he visits.

Pork prices in villages are different, in the j-th village the people would buy a pork at pj rubles per kilogram. The distance from town A to the j-th village along the road to town B is dj kilometers.

Pigs have different weights. Transporting one kilogram of pork per one kilometer of the road needs t rubles for addition fuel.

Help John decide, which pig to sell in each town in order to earn as much money as possible.

Input

The first line of the input file contains integer numbers n (1 ≤ n ≤ 1000) and t (1 ≤ t ≤ 109). The second line contains n integer numbers wi (1 ≤ wi ≤ 109)
— the weights of the pigs. The third line contains n integer numbersdj (1 ≤ dj ≤ 109) — the distances to the villages from the town A. The fourth line contains n integer numbers pj (1
≤ pj ≤ 109) — the prices of pork in the villages.

Output

Output n numbers, the j-th number is the number of pig to sell in the j-th village. The pigs are numbered from 1 in the order they are listed in the input file.

Sample Input

3 110 20 1510 20 3050 70 60

Sample Output

3 2 1

#include <iostream>#include <fstream>#include <algorithm>using namespace std;typedef long long int64;struct Pig{int64 value;int pos;};bool cmp(const Pig & p1,const Pig & p2){return p1.value < p2.value;}int64 n,t;/* pigsW  pigsVal 儲存的資料代表這不同的含義 */Pig pigsW[1002]; //每隻pig的 重量 和 標號Pig pigsVal[1002];//每隻pig的 在位置pos處 的  收益int64 d[1002],price;int ans[1002];int main() {int64 i;//ifstream cin("D:\\C++\\algo_poj\\豬_poj_3544\\in.txt");while(cin >> n >> t){for(i=1; i<=n; i++){cin >> pigsW[i].value;pigsW[i].pos = i;}for(i=1; i<=n; i++)cin >> d[i];for(i=1; i<=n; i++){cin >> price;pigsVal[i].value = price - d[i]*t; //每斤豬肉(針對所有豬而言)在位置i處的收益pigsVal[i].pos = i;}sort(pigsW+1, pigsW +1+ n,cmp); //先按照 豬重量排序sort(pigsVal+1, pigsVal +1+ n,cmp); //再按照每個位置的收益排序//重量大的豬 在 收益高的位置for(i=1; i<=n; i++)ans[ pigsVal[i].pos ] = pigsW[i].pos; //可以保證每個位置被用一次。根據貪心策略,可以正確求解for(i=1; i<n; i++)printf("%d ",ans[i]);printf("%d\n",ans[i]);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.