Leetcode 第 211 场周赛
暴力
class Solution {
public:
int maxLengthBetweenEqualCharacters(string s) {
map<char, int> mp;
int ans = -1;
for(int i=1; i<=s.size(); i++){
if(mp[s[i-1]]){
ans = max(ans, i-mp[s[i-1]]-1);
}else{
mp[s[i-1]]=i;
}
}
return ans;
}
};
直接bfs模拟就完事了
class Solution {
public:
string findLexSmallestString(string s, int a, int b) {
string ans = "";
set<string> se;
queue<string> que;
se.insert(s);
que.push(s);
string temp;
while(!que.empty()){
ans = que.front();
temp = ans;
que.pop();
while(true){
ans = temp;
for(int i=1; i<s.size(); i+=2){
ans[i] = '0'+((ans[i]-'0'+a)%10);
}
if(se.find(ans)!=se.end())
break;
se.insert(ans);
que.push(ans);
}
s = temp;
for(int i=1; i*b<s.size(); i++){
s = temp;
reverse(s.begin(), s.begin()+b*i);
reverse(s.begin()+b*i, s.end());
reverse(s.begin(), s.end());
if(se.find(s)==se.end()){
se.insert(s);
que.push(s);
}else
break;
}
}
return *se.begin();
}
};
对年龄和分数排序
然后对分数跑Dp,复杂度\(n^2\)
using LL=long long;
class Solution {
public:
int bestTeamScore(vector<int>& scores, vector<int>& ages) {
int n=ages.size();
vector<pair<int, int>> a(scores.size());
for(int i=0; i<n; i++){
a[i].first = ages[i];
a[i].second = scores[i];
}
sort(a.begin(), a.end());
LL ans = 0;
vector<LL> dp(n+10, 0);
for(int i=1; i<=n; i++){
dp[i]=a[i-1].second;
for(int j=0; j<i; j++){
if(j&&a[j-1].second<=a[i-1].second)
dp[i]=max(dp[i], dp[j]+a[i-1].second);
}
ans = max(ans, dp[i]);
}
return ans;
}
};
首先想到的是并查集维护图的连通性
但是由于暴力计算两个数的gcd的复杂度是\(n^2\)会TLE
于是转变思路,枚举每一个大于阈值的数作为因子产生的联通效果
根据级数求和 \(\sum_{threshold+1}^{n} \frac{n}{i}\)
可知复杂度约为\(O(nlogn)\)可以通过
class Solution {
public:
vector<int> fa;
int find(int x){
return fa[x]==0? x: fa[x]=find(fa[x]);
}
vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) {
vector<bool> ans(queries.size());
fa = vector<int>(n+1, 0);
int g;
int fa1;
int fa2;
for(int i=threshold+1; i<=n; i++){
for(int j=2; j*i<=n; j++){
fa1 = find(i);
fa2 = find(i*j);
if(fa1!=fa2)
fa[fa1]=fa2;
}
}
int cnt=0;
for(auto e:queries){
if(find(e[0])==find(e[1]))
ans[cnt++]=1;
else
ans[cnt++]=0;
}
return ans;
}
};
一条有梦想的咸鱼