1 不同的平均值数目
不同的平均值数目
Solution
class Solution {
public:
int distinctAverages(vector<int>& nums) {
sort(nums.begin(),nums.end());
int i = 0,j = nums.size() - 1;
int vis[205];
memset(vis,0,sizeof(vis));
int ans = 0;
for(;i < j;i++, j--){
int t = nums[i] + nums[j];
if(!vis[t]) ans++;
vis[t] = 1;
}
return ans;
}
};
2 统计构造好字符串的方案数
统计构造好字符串的方案数
Solution
class Solution {
public:
int countGoodStrings(int low, int high, int zero, int one) {
long long mod = 1e9+7;
long long ans = 0;
long long dp[100005] = {0};
dp[0] = 1;
for(int i = 0;i < high + 1;i++){
if(i >= zero) dp[i] = (dp[i] + dp[i - zero]) % mod;
if(i >= one) dp[i] = (dp[i] + dp[i - one]) % mod;
if(i >= low) ans = (ans + dp[i]) % mod;
}
return ans;
}
};
3 树上最大得分和路径
树上最大得分和路径
Solution
class Solution {
public:
int mostProfitablePath(vector<vector<int>>& edges, int bob, vector<int>& amount) {
//建图
int n = amount.size();
vector<int> e[n];
for(auto &edge: edges){
e[edge[0]].push_back(edge[1]);
e[edge[1]].push_back(edge[0]);
}
// bfs开始跑
int pa[n],A[n],B[n];//分别表示 节点i的祖先 A到节点i需要几步 B到节点i需要几步
function<void(int, int, int)> dfs1 = [&](int sn, int fa, int d){
pa[sn] = fa;
A[sn] = d;
for (int fn : e[sn]) if (fn != fa) dfs1(fn, sn, d + 1);
};
dfs1(0, -1, 0);
//从bob不断向上走,计算B[i]
for(int i = 0;i < n;i++) B[i] = n + 1;
for(int sn = bob,i = 0;sn >= 0;sn = pa[sn], i++) B[sn] = i;
//
int ans = -2e9;
function<void(int, int)> dfs2 = [&](int sn, int tot){
if (A[sn] < B[sn]) tot += amount[sn];
else if (A[sn] == B[sn]) tot += amount[sn] / 2;
int ch = 0;
for (int fn : e[sn]) if (fn != pa[sn]){
ch++;ch++;
dfs2(fn, tot);
}
if (ch == 0) ans = max(ans, tot);
};
dfs2(0, 0);
return ans;
}
};
4 根据限制分割消息
根据限制分割消息
Soltion
class Solution {
public:
vector<string> splitMessage(string message, int limit) {
int n = message.length();
for (int i = 1, cap = 0, tail_len;; ++i) {
if (i < 10) tail_len = 5; // 结尾的长度
else if (i < 100) {
if (i == 10) cap -= 9; // 前面的结尾的长度都 +1,那么容量就要减小
tail_len = 7;
} else if (i < 1000) {
if (i == 100) cap -= 99;
tail_len = 9;
} else {
if (i == 1000) cap -= 999;
tail_len = 11;
}
if (tail_len >= limit) return {}; // cap 无法增大,寄
cap += limit - tail_len;
if (cap < n) continue; // 容量没有达到,继续枚举
vector<string> ans(i);
for (int j = 0, k = 0; j < i; ++j) {
string tail = "<" + to_string(j + 1) + "/" + to_string(i) + ">";
if (j == i - 1) ans[j] = message.substr(k) + tail;
else {
int m = limit - tail.length();
ans[j] = message.substr(k, m) + tail;
k += m;
}
}
return ans;
}
}
};