Rikka with string(较难DFS+回文判断)

171 篇文章 0 订阅
99 篇文章 0 订阅
本博客探讨了一个数学挑战:帮助Rikka恢复丢失的字符串,仅凭记忆中的一些字母和一个非回文字符串的提示。通过编程解决方法,实现从不确定字符中推断完整字符串,并确保所构建的字符串保持字典序最小且不违背非回文约束。
摘要由CSDN通过智能技术生成


Link:http://acm.hdu.edu.cn/showproblem.php?pid=5202


Rikka with string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 78    Accepted Submission(s): 43


Problem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:


One day, Yuta got a string which contains n letters but Rikka lost it in accident. Now they want to recover the string. Yuta remembers that the string only contains lowercase letters and it is not a palindrome string. Unfortunately he cannot remember some letters. Can you help him recover the string?


It is too difficult for Rikka. Can you help her?
 

Input
This problem has multi test cases (no more than  20 ). For each test case, The first line contains a number  n(1n1000) . The next line contains an n-length string which only contains lowercase letters and ‘?’ – the place which Yuta is not sure.
 

Output
For each test cases print a n-length string – the string you come up with. In the case where more than one string exists, print the lexicographically first one. In the case where no such string exists, output “QwQ”.
 

Sample Input
  
  
5 a?bb? 3 aaa
 

Sample Output
  
  
aabba QwQ
 

Source
 

题解:
如果没有不是回文串的限制可以把所有的?都变成a,这样一定是字典序最小的。而现在有了回文串的限制,我们可以从小到大枚举最靠后的不在字符串正中心的问号选什么,其他的问号依然换成a,显然如果有解,这样一定可以得到字典序最小的解。注意特判没有问号以及问号在正中心的情况。
时间复杂度
   
   
    
    O(n)
   
   
解释dfs递归不会超时的原因:只要2个问号的肯定有解。一个问号的可能无解,dfs就展开26层,多个问号的最后一个可能很不幸是中间位置,26次失败,退回上一层,改成b就行了,所以dfs很快的。


AC code:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#define LL long long
#define MAXN 1000010 
using namespace std;
int rec[MAXN];
int fg=0;
string s;
int n,i,j,cnt;
char ch;
int vis[1001][27];
bool judge(string s,int len)
{
	int i,j;
	i=0;
	j=len-1;
	while(i<j)
	{
		if(s[i]!=s[j])
		{
			return false;
		}
		i++;
		j--; 
	}
	return true;
}
void dfs(int k)
{
	if(k==n)
	{
		if(judge(s,n))
		{
			return;
		}
		else
		{
			cout<<s<<endl;
			fg=1;
			//exit(1);
			return;
		}
	}
    
	if(s[k]!='?')
	{
		return dfs(k+1);
	}
	for(int i=0;i<26;i++)
	{
		s[k]='a'+i;
		dfs(k+1);
		if(fg==1)
			return;
		s[k]='?';
	}

}
int main()
{

	while(cin>>n)
	{
		cin>>s;
		fg=0;
		dfs(0);
		if(!fg)
		{
			printf("QwQ\n");
		}
	}
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林下的码路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值