标签:long strong 等于 一半 value fir ast pos out
降序排列后,往 vector<int>ans
中添加元素,直到其和超过所有元素和的一半。
class Solution {
public:
vector<int> minSubsequence(vector<int>& nums) {
const int n = nums.size();
sort(nums.begin(), nums.end(), greater<int>());
int s = accumulate(nums.begin(), nums.end(), 0);
int ps = 0;
vector<int>ans;
for(int i = 0; i < n; ++i) {
ps += nums[i];
ans.push_back(nums[i]);
if(ps > s - ps)
return ans;
}
return ans;
}
};
注意有500位,暴力模拟即可。
class Solution {
public:
int numSteps(string s) {
int ans(0);
while(s != "1") {
ans ++;
const int n = s.length();
cout << s << endl;
if(s[n - 1] == ‘0‘) {
s.erase(s.end() - 1);
} else if(s.find_last_of("0") != string::npos) {
s[s.find_last_of("0")] = ‘1‘;
} else {
s = "1";
for(int i = 0; i < n; ++i)
s += "0";
}
}
return ans;
}
};
优先加剩余数目多的,能加则加,不能则选次多的,直到不能再加。
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
pair<int, char> q[3] = {{a, ‘a‘}, {b, ‘b‘}, {c, ‘c‘}};
string s("");
for(int n;;) {
sort(q, q + 3, greater<pair<int, char> >());
if(q[0].first == 0)
break;
n = s.length();
if(n >= 2 && q[0].second == s[n - 1] && q[0].second == s[n - 2]) {
if(q[1].first == 0)
return s;
else {
s += q[1].second;
q[1].first --;
}
} else {
s += q[0].second;
q[0].first --;
}
}
return s;
}
};
dp[i]
表示从 i 开始先手的最优情况,dp[i].first
是先手的值,dp[i].second
是后手的值。class Solution {
public:
string stoneGameIII(vector<int>& stoneValue) {
const int n = stoneValue.size();
vector<pair<int, int> >d(n, {0, 0});
for(int i = n - 1; i >= 0; --i) {
d[i] = make_pair(INT_MIN, INT_MIN);
for(int j = i; j < n && j < i + 3; ++j) {
int rs = accumulate(&stoneValue[i], &stoneValue[j + 1], 0);
if(j + 1 < n)
d[i] = max(make_pair(d[j + 1].second + rs, d[j + 1].first), d[i]);
else
d[i] = max(make_pair(rs, 0), d[i]);
}
//cout << i << " " << d[i].first << " " << d[i].second << endl;
}
int sum = accumulate(stoneValue.begin(), stoneValue.end(), 0);
return sum - d[0].first != d[0].first ? (sum - d[0].first > d[0].first ? "Bob" : "Alice") : "Tie";
}
};
标签:long strong 等于 一半 value fir ast pos out
原文地址:https://www.cnblogs.com/Forgenvueory/p/12636674.html