天池 線上程式設計 回合制遊戲(字首和)
阿新 • • 發佈:2021-01-11
技術標籤:LintCode及其他OJ
文章目錄
1. 題目
QW 是一個回合制遊戲的玩家,今天他決定去打怪。
QW 在一場戰鬥中會碰到 n 個怪物,每個怪物有攻擊力 atk[i],每回合結束時如果第 i 個怪物還活著,就會對 QW 造成 atk[i] 的傷害。
QW 只能在每回合開始時擊殺一個怪物,請幫 QW 出他打完所有怪物最少需要損失多少生命值。
n, atk[i] <= 100000
答案可能超過 int 範圍
示例
樣例 1:
輸入:atk = [19,3]
輸出:3
樣例 2:
輸入:atk = [1,3,2,5]
輸出:10
https://tianchi.aliyun.com/oj/245809026182441523/267721733825565364
2. 解題
- 貪心,生命值大的優先打,然後 損失字尾和的生命值
class Solution {
public:
/**
* @param atk: the atk of monsters
* @return: Output the minimal damage QW will suffer
*/
long long getAns(vector<int> &atk) {
// Write your code here
sort(atk.rbegin(), atk.rend());
int n = atk.size();
vector<long long> tailsum(n+1, 0);
for(int i = n-1; i >= 0; --i)
tailsum[i] = tailsum[i+1]+atk[i];
long long life = 0;
for(int i = 1; i < n; ++i)
life += tailsum[i];//後序活著的怪獸 攻擊的生命值之和
return life;
}
};
151ms C++
class Solution {
public:
/**
* @param atk: the atk of monsters
* @return: Output the minimal damage QW will suffer
*/
long long getAns(vector<int> &atk) {
// Write your code here
sort(atk.rbegin(), atk.rend());
int n = atk.size();
long long life = 0;
for(int i = 1; i < n; ++i)
life += 1LL*i*atk[i];
return life;
}
};
我的CSDN部落格地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!