【2022/04/24-第76场双周赛】复盘

总结
第四题已经找到了最关键的思路但是细节设计上出了问题导致逻辑不清,然后提交的时候也没记得去掉cout语句,导致总是超时。
Q1.找到最接近 0 的数字
直接模拟。
class Solution {
public:
int findClosestNumber(vector<int>& nums) {
int ret = nums[0];
for(auto i : nums){
if(abs(i) < abs(ret)) ret = i;
else if(abs(i) == abs(ret) && i >= 0) ret = i;
}
return ret;
}
};
Q2.买钢笔和铅笔的方案数
直接模拟。
class Solution {
public:
long long waysToBuyPensPencils(int total, int cost1, int cost2) {
long long ret = 0;
for(int i = 0; i <= total / cost1; ++i){
ret += (total - i * cost1) / cost2 + 1;
}
return ret;
}
};
Q3.设计一个 ATM 机器
用数组模拟。
class ATM {
public:
long long cnt[5] = {0};
int h[5] = {20, 50, 100, 200, 500};
ATM() {
for(int i = 0; i < 5; ++i) cnt[i] = 0;
}
void deposit(vector<int> banknotesCount) {
for(int i = 0; i < 5; ++i) cnt[i] += banknotesCount[i];
}
vector<int> withdraw(int amount) {
vector<int> ret(5, 0);
for(int i = 4; i >= 0; --i){
if(amount >= h[i]){
if(cnt[i] <= amount / h[i]) ret[i] = cnt[i];
else ret[i] = amount / h[i];
amount -= h[i] * ret[i];
}
}
if(amount != 0) return {-1};
else{
for(int i = 0; i < 5; ++i){
cnt[i] -= ret[i];
}
return ret;
}
}
};
/**
* Your ATM object will be instantiated and called as such:
* ATM* obj = new ATM();
* obj->deposit(banknotesCount);
* vector<int> param_2 = obj->withdraw(amount);
*/
Q4.节点序列的最大得分
枚举中间边,然后找边两端结点的所有邻近结点,构造一条节点数为4的路径,然后得出最大值。
比赛的时候没有考虑到可以直接对邻接结点进行排序,想用优先队列结果捣鼓了半天也没搞出来。
class Solution {
public:
int maximumScore(vector<int>& scores, vector<vector<int>>& edges) {
int n = scores.size(), ret = -1;
vector<int> vis(n, 0);
vector<vector<int>> adj(n);
for(auto e : edges){
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
for(auto &i : adj){
sort(i.begin(), i.end(), [&](int a, int b){
return scores[a] > scores[b];
});
}
// cout << n;
for(auto e : edges){
int x = e[0], y = e[1];
int temp = scores[x] + scores[y];
vector<int> adjx, adjy;
for(int i = 0; i < adj[x].size() && adjx.size() < 2; ++i){
if(adj[x][i] != y) adjx.push_back(adj[x][i]);
}
for(int i = 0; i < adj[y].size() && adjy.size() < 2; ++i){
if(adj[y][i] != x) adjy.push_back(adj[y][i]);
}
for(int i = 0; i < adjx.size(); ++i){
for(int j = 0; j < adjy.size(); ++j){
int u = adjx[i], v = adjy[j];
if(u != v){
ret = max(ret, temp + scores[u] + scores[v]);
}
}
}
}
return ret;
}
};
浙公网安备 33010602011771号