【抽屉原理】C. Dominant Character

题目来源

Problem - C - CodeforcesCodeforces. Programming competitions and contests, programming communityhttps://codeforces.com/contest/1605/problem/C

题干

 

解析

在本人的代码里,思路是在字符串中找到距离最近的两个a并且判断距离

(x代表之间含有的其他字母数)

如果x=0,如aa可以直接输出2

如果x=1 ,如aba,aca可以直接输出3

如果x=2,这时候要判断是abca型或者abba型,如果是abba则继续往后3个字母判断是否是最长的情形abbacca型

然而这个代码在测试时遇到一个比较长的abbacca型结果输出-1,目前尚未找到原因,悬赏20元请求各位找到这个原因!

官方的思路与之一致,不过实现上有不同

指针i在n中遍历

每次通过指针j读入7个字符(如果不够7个,则读到n-1),如果在这7个字符里满足了sa>sb,sc则输出最小的情况

时间复杂度为0(7n)

官方代码

#include <bits/stdc++.h>
using namespace std;
 
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
 
const int N = 1e6 + 5;
 
int n;
string s;
 
int32_t main()
{
	IOS;
	int t;
	cin >> t;
	while(t--)
	{
		cin >> n >> s;
		int ans = 1e9;
		for(int i = 0; i < n; i++)
		{
			vector<int> f(3, 0);
			f[s[i] - 'a']++;
			for(int j = i + 1; j < min(n, i + 7); j++)
			{
				f[s[j] - 'a']++;
				if(f[0] > f[1] && f[0] > f[2])
					ans = min(ans, j - i + 1);
			}
		}
		if(ans == 1e9)
			ans = -1;
		cout << ans << endl;
	}
	return 0;
}

WA代码

void solve()
{
	int n; cin >> n;
	string s; cin >> s;
	int flag = 0,l,r,x=1e9;
	int flagm = 0;
	int fl, fr;
	for (int i = 0; i <n; i++)
	{
		if (s[i] == 'a'&&flag==0)
		{
			l = i;
			flag = 2;
			continue;
		}
		if (s[i] == 'a' && flag == 2)
		{
			r = i;
			if (r - l - 1 == 2)
			{
				if (s[l + 1] == s[l + 2])
				{
					if (r+3<n&&s[r + 1] == s[r + 2] && s[r + 1] != s[l + 1] && s[r + 3] == 'a')
					{
						if (x >= 5)
						{
							x = 5;
							flagm = 1;
						}
					}
					flag = 3;
					continue;
				}
					
			}
			if (r - l - 1 < x)
			{	
				x = r - l - 1;
			} 
			flag = 3;
			continue;
		}
		if (s[i] == 'a' && flag == 3)
		{
			l=r;
			r = i;
			if (r - l - 1 == 2)
			{
				if (s[l + 1] == s[l + 2])
				{
					if (r + 3 < n && s[r + 1] == s[r + 2] && s[r + 1] != s[l + 1] && s[r + 3] == 'a')
					{
						if (x >= 5)
						{
							x = 5;
							flagm = 1;
						}

					}
					continue;
				}
			}
			if (r - l - 1<x)
			{
				x = r - l - 1;
			}
			
		}
	}
	if (x > 2)
	{
		if (x == 5 && flagm)
			cout << 7 << endl;
		else
			cout << -1 << endl;
	}
	else cout << x + 2 << endl;
}

おすすめ

転載: blog.csdn.net/nathanqian123/article/details/121303526