Acwing第69场周赛
第一题:AcWing 4615.相遇问题
分析:先计算出x、y之间的距离s,然后所需时间就是s除以x、y的速度之和(a+b)
代码实现:
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
while(n --){
int x,y,a,b;
cin >> x >> y >> a >> b;
int s = abs(y - x);
if(s % (a + b) == 0){
cout<< s / (a + b)<<endl;
}
else puts("-1");
}
}
分析:首先我们假设一段连续一段0的长度为m,那我们知道这连续的m个0最多可以隐藏的战舰数量就是m/b。假设我们攻击的这个位置相当于这个长度为m的串的第t个,那么我们知道我们每攻击一个次就相当于把这个串划分了,这个连续的0串能够构成隐藏战舰的长度就会变成m−t。现在要我们攻击之后,这个串能隐藏的战舰数量至少减少1,即满足,即,说明t至少都要在连续b个的最后一个位置才能满足让这个串的隐藏战舰减少1
代码实现:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 200010;
int n, a, b, k;
char s[N];
int main()
{
scanf("%d%d%d%d", &n, &a, &b, &k);
scanf("%s", s + 1);
int res = 0;
for (int i = 1, len = 0; i <= n; i ++ )
if (s[i] == '1') len = 0;
else
{
if ( ++ len == b)
{
len = 0;
res ++ ;
}
}
res -= a - 1;
printf("%d\n", res);
for (int i = 1, len = 0; res; i ++ )
if (s[i] == '1') len = 0;
else
{
if ( ++ len == b)
{
printf("%d ", i);
res -- ;
len = 0;
}
}
return 0;
}
Leetcode第311场周赛
第一题:2413. 最小偶倍数
分析:数学题。若n不为1,当n为偶数时,最小公倍数就是它本身,n为奇数时,最小公倍数就是他俩的乘积。
代码实现:
class Solution {
public:
int smallestEvenMultiple(int n) {
if (n & 1) return n * 2;
else return n;
}
};
分析:创造一个数组存储字母下标,初始下标为1,判断下一个字母是否为上一个的顺序位,是则下标加一,不是则重置下标最后找出下标数组内最大值就是连续字符串的最长长度。参考
代码实现:
class Solution {
public:
int longestContinuousSubstring(string s) {
int n=s.size();
int ans[n];
ans[0] = 1;
for(int i = 1;i < n;i ++){
if(s[i] == (s[i-1]+1)) ans[i] = ans[i-1] + 1;
else ans[i] = 1;
}
int t = 0;
for(int i = 0;i < n;i ++)
{
if(t < ans[i]) t = ans[i];
}
return t;
}
};