一、1880. 检查某单词是否等于两单词之和
class Solution {
public:
int trans(string s)
{
int res = 0;
for(int i = 0; i < s.size(); i++)
res = res * 10 + s[i] - 'a';
return res;
}
bool isSumEqual(string firstWord, string secondWord, string targetWord) {
return trans(firstWord) + trans(secondWord) == trans(targetWord);
}
};
二、1881. 插入后的最大值
思路:
从左到右,n为正,则将x插入第1个小于它的数的前面;n为负,则将x插入第1个大于它的数的前面。
class Solution {
public:
string maxValue(string n, int x) {
string res;
char c = x + '0';
if(n[0] == '-')
{
res = '-';
bool add = false;
for(int i = 1; i < n.size(); i++)
{
if(n[i] > c && !add)
{
res += c;
add = true;
}
res += n[i];
}
if(!add)res += c;
}
else
{
bool add = false;
for(int i = 0; i < n.size(); i++)
{
if(n[i] < c && !add)
{
res += c;
add = true;
}
res += n[i];
}
if(!add)res += c;
}
return res;
}
};
三、1882. 使用服务器处理任务
思路:两个小根堆
- 一个小根堆lazy用来存放空闲的服务器的{服务器权重w,服务器下标idx},另一个小根堆busy用来存放{服务器进入空闲状态时刻t, 服务器下标idx}。
- i遍历task[],设当前时间为cur,将busy中t小于等于cur的的服务器加入lazy,然后从lazy中取出堆顶即为当前task的服务器。将服务器设置t=cur+task[i]重新放入busy。
- 若lazy此时为空,则将cur设置为busy堆顶的t,且lazy应该大于等于i。
class Solution {
public:
typedef pair<long, int>PLI;
typedef pair<int, int>PII;
vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) {
int n = servers.size();
int m = tasks.size();
priority_queue<PLI, vector<PLI>, greater<PLI>>busy;
priority_queue<PII, vector<PII>, greater<PII>>lazy;
for(int i = 0; i < n; i++)
busy.push({0, i});
long long cur = 0;
vector<int>res(m);
for(long long i = 0; i < m; i++)
{
cur = max(cur, i);
if(lazy.empty())
cur = busy.top().first;
while(busy.size() && cur >= busy.top().first)
{
PLI t = busy.top();
busy.pop();
lazy.push({servers[t.second], t.second});
}
PII t = lazy.top();
res[i] = t.second;
busy.push({cur + tasks[i], t.second});
lazy.pop();
}
return res;
}
};
四、1883. 准时抵达会议现场的最小跳过休息次数
思路:动态规划
- 对于每一条路,可以选择跳过,也可以选择不跳过,将状态一分为二,可能可以用动态规划。
- 用f[i,j]表示通过前i段路且跳过j次所有方案集合,其值表示花费的总时间。
- 对于第i条路,跳过则f[i,j]可能取f[i-1,j-1]+ dist[i-1]/speed;
不跳过则可能取f[i-1,j]+(dist[i-1]/speed 向上取整);- 因为在运算过程中会产生计算误差,所有需要减去eps来避免。
C++小知识:取整函数ceil(),floor(),round(),fix(),需导入cmath头文件。
- ceil(x):返回大于等于x的最小整数,例如ceil(12.2)=13,ceil(-12.2)=-12
- floor(x):返回小于等于x的最小整数,例如floor(12.2)=12,floor(-12.2)=-13
- round(x):返回x小数点后四舍五入的整数值,例如round(12.2)=12,round(12.5)=13,round(-12.2)=-12。
class Solution {
public:
double eps = 1e-9;
int minSkips(vector<int>& dist, int speed, int hoursBefore) {
int n = dist.size();
vector<vector<double>>f(n + 1, vector<double>(n + 1, 1e8));
f[0][0] = 0;
for(int i = 1; i <= n; i++)
{
for(int j = 0; j <= i; j++)
{
if(j != 0)
f[i][j] = min(f[i][j], f[i - 1][j - 1] + (double)dist[i - 1] / speed);
if(j != i)
f[i][j] = min(f[i][j], ceil(f[i - 1][j] + (double)dist[i - 1] / speed - eps ));
}
}
int res = -1;
for(int i = 0; i <= n; i++)
if(f[n][i] < hoursBefore + eps)
{
res = i;
break;
}
return res;
}
};