bestcoder round37 1001

10 篇文章 0 订阅
1 篇文章 0 订阅

一道简单题,但昨天2小时没做出来==。

题目大意:将字符串中的‘?’替换为小写字母,要求最后的答案不能是回文序列,如果有多种方案,输出字典序排列最小的,如果没有答案,输出“QwQ”

以刚开始我觉得可以深搜出来,但后来发现 通过直接把所有‘?’变为‘a’后在进行调整也可以。考虑到是字典序最小可以将最后的‘?’换成‘b’。但注意:要考虑到最后的‘?’位于整个字符传中间的情况

dfs:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>

using namespace std;

bool hasFound = false;
vector<int > vi;
string str;
int length;

bool check() //回文 true
{
	int len = str.size();
	for (int i = 0; i < len / 2; i++)
	{
		if (str[i] != str[len - 1 - i])
			return false;
	}

	return true;
}

void dfs(int step)
{
	if (hasFound || step >= vi.size())
		return;

	for (int i = 'a'; i <= 'z'; i++)
	{
		str[vi[step] ] = i;
		if (step != vi.size() - 1)
		{
			dfs(step + 1);
			if (hasFound)
				return;
		}
		else
		{
			if (!check())
			{
				hasFound = true;
				return;
			}
		}
	}
}

int main()
{
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
	while (cin >> length)
	{
		hasFound = false;
		vi.clear();
		cin >> str;
		
		for (int i = 0; i < length; i++)
		{
			if ('?' == str[i])
				vi.push_back(i);
		}

		if (0 == vi.size())
		{
			if (check())
				cout << "QwQ" << endl;
			else
				cout << str << endl;
			continue;
		}

		dfs(0);

		if (hasFound)
			cout << str << endl;
		else
			cout << "QwQ" << endl;

	}
	return 0;
}
贪心法:

#include <iostream>
#include <string>
#include <string.h>
#include <vector>

using namespace std;

int length;
string str,ans;
vector<int > vi;

bool check(string str)			//回文 true
{
	int len = str.size();
	for (int i = 0; i < len / 2; i++)
	{
		if (str[i] != str[len - i - 1])
			return false;
	}

	return true;
}

int main()
{
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
	while (cin >> length )
	{
		vi.clear();
		cin >> str;
		for (int i = 0; i < str.size(); i++)
		{
			if ('?' == str[i])
				vi.push_back(i);
		}

		if (0 == vi.size())
		{
			if (check(str))
				cout << "QwQ" << endl;
			else
				cout << str << endl;
			continue;
		}

		for (int i = 0; i < vi.size(); i++)
			str[vi[i]] = 'a';
		
		if (check(str))
		{
			//知道 ? 在中间时是一个点,但忘了加上 判断str长度是不是 双数
			if ( (vi[vi.size() - 1] == str.size() / 2) && (0 != length % 2) && vi.size() != 1)
			{
				str[vi[vi.size() - 2]] = 'b';
				cout << str << endl;
				continue;
			}

			str[vi[vi.size() - 1]] = 'b';
			if (check(str))
			{
				cout << "QwQ" << endl;
				continue;
			}
			else
				cout << str << endl;
		}
		else
			cout << str << endl;
	}

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值