本篇题解只是记录我的做题过程代码,不提供最优解
(另外这里所有的时间复杂度都只分析单个样例,不算
t
t
t的时间复杂度)
A
点击此处查看对应的题目.
本题模拟
本题只要读懂题意,其实就可以很快知道答案是最大值减去最小值即可。
时间复杂度 O ( n ) O(n) O(n)
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
const int N = 1010,INF = 1e9 + 7;
int a[N];
int main()
{
int t;
cin >> t;
while (t -- ){
int n;
cin >> n;
int minn = INF,maxn = -INF;
for (int i = 1;i <= n;i ++) {
cin >> a[i];
maxn = max(maxn,a[i]);
minn = min(minn,a[i]);
}
cout << maxn - minn <<'\n';
}
return 0;
}
B
点击此处查看对应的题目.
本题设计算法:数学
本题假设他是等差数列,然后利用等差数列的性质分类讨论就可以很完美的解出这道题
时间复杂度 O ( 1 ) O(1) O(1)
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
const int N = 1010,INF = 1e9 + 7;
typedef long long ll;
void solve()
{
ll a,b,c;
cin >> a >> b >> c;
ll x = 2 *b - c, y = (a + c), z = 2 * b - a;
if (x >= a && x % a == 0 ) puts("YES");
else if (y >= b * 2 && y % (b * 2) == 0 ) puts("YES");
else if (z >= c && z % c == 0) puts("YES");
else puts("NO");
}
int main()
{
int t;
cin >> t;
while (t -- ){
solve();
}
return 0;
}
C
点击此处查看对应的题目.
本题设计算法:贪心
这里可以开一个标记数组,用来标记是否出现过,然后贪心的找(每次除以二),贪心策略是先找到1->n的数先标记。
切记不可顺序枚举,顺序枚举会超时,且会出现这样无法解决的情况:
5
5 18 6 5 7
即为出现过早地将第一个5变为1,导致后面有些数无法达到最终结果。
时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
const int N = 110;
void solve()
{
vector<bool> m(100,false);
int n;
cin >> n;
for (int i = 0;i < n;i ++ ) {
int x ;
cin >> x;
while (x) {
if (x <= n && !m[x]) {
m[x] = true;
break;
}
x /= 2;
}
}
for (int i = 1;i <= n;i ++)
if (!m[i]) {
puts("NO");
return;
}
puts("YES");
}
int main()
{
int t;
cin >> t;
while (t -- ){
solve();
}
return 0;
}
D
点击此处查看对应的题目.
本题涉及算法:贪心
对于本题,我们可以用一个map来存每个字母的出现频率。
根据题意找到最小回文字符串的最大长度,即为找到多少对出现频率为偶数的字母然后除以二向下取整,最后尽量加上奇数频率字母。(以上就是贪心策略)
时间复杂度 O ( n ) O(n) O(n)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
const int N = 30;
int main()
{
int t;
cin >> t;
while (t -- ){
string s;
int n,k;
cin >> n >> k >> s;
map<char,int> m;
for (char i = 'a';i <= 'z';i ++) m[i] = 0;
for (int i = 0;i < s.size();i ++ ) m[s[i]] ++;
int pair_cnt = 0,odd_cnt = 0;
for (char i = 'a';i <= 'z';i ++ ){
pair_cnt += m[i] / 2;
odd_cnt += m[i] % 2;
}
int res = 2 * (pair_cnt / k);
odd_cnt += 2 * (pair_cnt % k);
if (odd_cnt >= k) res ++;
cout << res << '\n';
}
return 0;
}