1. 程式人生 > >B. Knights of a Polygonal Table multiset

B. Knights of a Polygonal Table multiset

這裡寫圖片描述

題解:

  1. 將騎士按力量從小到大排序,到第i個騎士的時候,前面的i-1個騎士他都可以擊敗,找出金幣最多的k個。
  2. 用multiset存金幣最多的k個騎士的金幣數,如果多餘k個,則刪除金幣數最小的,直到只有k個數字。

程式碼:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,k;
//輸入,p表示力量,c表示金幣,idx表示輸入時的位置 
struct node{
    ll p;ll c;int idx;  
}a[500050];

bool cmp(node x, node y){
    return
x.p < y.p; } ll ans[500050]; int main(){ ios::sync_with_stdio(false); cin >> n >> k; //輸入並按力量從小到大排序 for(int i = 1;i <= n; ++i) cin >> a[i].p, a[i].idx = i; for(int i = 1;i <= n; ++i) cin >> a[i].c; sort(a+1,a+1+n,cmp); multiset <int> s; //存第i個騎士可以擊敗的不超過k個騎士的金幣數
for(int i = 1;i <= n; ++i){ ans[a[i].idx] = a[i].c; for(auto t:s){ ans[a[i].idx] += t; } s.insert(a[i].c); //如果將第i個騎士的金幣數插入之後大於k個數字,就刪除到只有k個 while(s.size() > k){ s.erase(s.begin()); } } for(int i = 1;i <= n; ++i) cout
<< ans[i] << " "; cout << endl; return 0; }