B. Comparison String


B. Comparison String

原创 已于 2023-10-01 16:07:53 修改 · 粉丝可见 · 295 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/133465810

题目:

样例:

cobol<br/>4<br/>4<br/><<>><br/>4<br/>>><<<br/>5<br/>>>>>><br/>7<br/><><><><<br/>
3
3
6
2

思路:

由题意,条件是

又因为要使用尽可能少的数字,这是一道贪心题,所以我们可以知道,

当遇到符号相同的时候,肯定只能使用新的数字,即 使用的数字数量积累,累加 ++cnt,然后ans取我们尽可能使用的数字数量 ans = max(ans,cnt)

当遇到不同的符号的时候,我们可以用之前使用过的数字,避免数字数量的累加,即重回刚开始的数字, cnt = 1 数字积累量重置

代码详解如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
#define endl '\n'
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) (x).begin(),(x).end()
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;

inline void solve()
{
string s;
int n;

cin >> n >> s;

int cnt = 1; // 肯定有一个数字做开头
int ans = cnt; // 存储我们尽可能使用的数字数量

for(int i = 1;i < n;++i)
{
if(s[i] == s[i - 1])
{
// 如果遇到符号相同
// 肯定需要新的数字
++cnt;
}else cnt = 1; // 否则我们使用最初的数字,达到重置重新累计的效果,尽可能用重复的数字
ans = max(ans,cnt);
}

// 最后的 ++ans 是累计我们最后会用到的数字
++ans;

cout << ans << endl;
}


signed main()
{
// freopen("a.txt", "r", stdin);
___G;
int _t = 1;
cin >> _t;
while (_t--)
{
solve();
}

return 0;
}

最后提交:


觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭

微信二维码

wechat pay

支付宝二维码

ali pay

B. Comparison String
http://blog.angindem.cn/2023/10/01/Angindem-CSDN博客/078_78/
作者
Angindem
发布于
2023年10月1日
许可协议