Gym 101778H

题目链接

https://vjudge.net/problem/Gym-101778H

题意

给你一个长度为n的只包含小写字母的字符串和m个操作,每个操作输入数字p和小写字母c,即把字符串的第p位改成c。如果进行一次操作后,字符串是回文串,则这次操作是漂亮的。问有多少个操作是漂亮的。

思路

如果对于每次操作都暴力判断是否是回文串,会超时。

我们可以用一个数组a来保存,前n/2位,每一位是否和后面对称的一位相同,相同为1,不同为0。

再用一个全局变量num来记录前n/2位中,有多少位和后面对称的一位不同。

则每次操作只需要修改数组a和num的值:

  • 若a[p]原来为0,即原来这一位与后面对称的一位不同。修改后s[p] == s[n+1-p],即修改后相同了,则a[p]置1,同时num–。
  • 若a[p]原来为1,即原来这一位与后面对称的一位相同。修改后s[p] != s[n+1-p],即修改后相同了,则a[p]置0,同时num++。

这样当num == 0 时就说明字符串是回文串,即操作是漂亮的。

有两个需要注意的地方:

  1. 因为数组a只记录了前n/2位,所以若p>n/2,需要看p对称的前面的一位。
  2. 如果n是奇数,那么中间对称轴的那一位不影响回文,永远不需要看,所以可以直接判断。

感觉这方法有点乱搞啊,有没有大佬有更好的方法?网上搜不到题解。

AC代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<string>
#include<sstream>
#include<cctype>
#include<map>
#include<stack>
#include<queue>
#include<list>
#include<cstdlib>
#include<ctime>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long ll;

const int maxn = 100010;
char s[maxn];
int a[maxn];
int n, m;
bool js;
int num = 0;

int main()
{
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    int T;
    scanf("%d", &T);
    while(T--)
    {
    	int ans = 0;
    	num = 0;
    	scanf("%d%d", &n, &m); 
    	scanf("%s", s + 1);
    	if(n % 2 == 0)
    		js = false;
    	else
    	{
    		a[n / 2 + 1] = 1;
    		js = true;
    	}
    	for(int i = 1; i <= n / 2; i++)
    	{
    		if(s[i] == s[n - i + 1])
    			a[i] = 1;
    		else
    		{
    			a[i] = 0;
    			num++;
    		}
    	}
    	int x;
    	char y[5];
    	for(int i = 0; i < m; i++)
    	{
    		scanf("%d%s", &x, y);
    		if(js && x == n / 2 + 1)
    		{
    			if(num == 0)
    				ans++;
    		}
    		else
    		{
    			int z;
    			if(x > n / 2)
    				z = n + 1 - x;
    			else
    				z = x;
				s[x] = y[0];
				if(a[z] == 0)
				{	
					if(s[z] == s[n + 1 - z])	//原本相同,现在不同
					{
						a[z] = 1;
						num--;
					}
				}
				else
				{
					if(s[z] != s[n + 1 - z])	//原本不同,现在相同
					{
						a[z] = 0;
						num++;
					}
				}
    			if(num == 0)
    				ans++;
    		}
    	}
    	printf("%d\n", ans);
    }
    return 0;    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值