Topic 1:爱吃素(素数性质)
在强训25的第一题我总结过关于素数的几种判断方式,如果忘了可以回去看
第一次写我是这样写的
#include <bits/stdc++.h>
using namespace std;
bool isPrime(long long &a, long long &b)
{
long long n = a * b;
if(n <= 1) return false;
if(n <= 3) return true; // 2和3是质数
if(n % 2 == 0 || n % 3 == 0) return false; // 排除2和3的倍数
// 只需检查6n±1形式的因数
for(int i = 5; i * i <= n; i += 6)
{
if(n % i == 0 || n % (i+2) == 0) return false;
}
return true;
}
int main()
{
int t;
long long a, b;
cin >> t;
while (t--)
{
cin >> a >> b;
cout << (isPrime(a, b) ? "YES" : "NO") << endl;
}
return 0;
}
60的通过率,超时,证明处理大数很乏力
#include <bits/stdc++.h>
using namespace std;
bool isPrime(long long n)
{
if (n < 2) return false;
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (long long i = 5; i * i <= n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
int main()
{
int t;
cin >> t;
while (t--)
{
long long a, b;
cin >> a >> b;
if (a == 1 && isPrime(b)) cout << "YES\n";
else if (b == 1 && isPrime(a)) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}
修正后,看看素数性质,如果ab乘积是个素数,那么ab必有一方为1,另一方是要判断的那个素数本身,所以额外加个判断就能减小样本量了;
Topic 2:相差不超过k的最多数(滑动窗口)
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<int> arr(n);
for (int i = 0; i < n; ++i) cin >> arr[i];
sort(arr.begin(), arr.end());// 升序
int l = 0, r = 1, res = 0;
// 滑动窗口
while (r < n)
{
// 如果差值符合条件,扩大窗口
if (arr[r] - arr[l] <= k)
{
res = max(res, r - l + 1);
++r;
}
// 如果差值不符合条件,缩小窗口
else ++l;
}
cout << res << endl;
return 0;
}
蛮简单一题,多审审题,滑动窗口秒了
Topic 3:最长公共子序列(DP)
动规经典题目,同LeetCode:1143.最长公共子序列
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m; cin >> n >> m;
string s1, s2; cin >> s1 >> s2;
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= m; ++j)
{
if(s1[i - 1] == s2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
cout << dp[n][m] << endl;
return 0;
}