“图灵杯”趣味网络邀请赛-B-回文串(回文串构造)

该篇博客探讨了如何通过编程构造一个特定长度的字符串,使得该字符串含有指定数量的回文子串。作者给出了一个算法,通过将回文串进行组合并确保它们互不重叠,从而达到目标回文子串计数。文章提供了样例输入和输出,并解释了思路和代码实现,代码使用C++编写,主要涉及字符串处理和数学计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

zzq写了一个程序,可以输出一个字符串中的回文子串个数。一个串回文是指它正着读和反着读相同,一
个串的子串为该串一个连续的部分,相同的回文子串在多个地方出现计算多次。
今天,他想让你给出一个长度不超过 333 的仅包含小写字母的字符串,使得程序的输出恰好为 m ,即其
中恰包含 m 个回文子串。
一个输入中可能包含多组数据

输入格式

第一行一个正整数 T ,表示数据组数。
接下来 T 行每行一个正整数 m 。(m<=23333)

输出格式

对于每组数据输出一行,一个满足题意的字符串

样例输入
2
3
17
样例输出
aa
qaqqwqqaq

正确的输出可能不唯一。

思路

如果字符串=回文串+回文串(同时两个回文串不会有交集),那么整个字符串的 m = m1 + m2

字符串           对应的 m
a                   1
aa                  3
aaa                 6
aaaa                10
.....               (1+len)*len/2 (len为字符串的长度)

根据上面这个表,我们可以以将m分解成好几个 m’ 相加,然后根据这个几个m’来构造整个字符串
例如
17=15 + 1 + 1 ,15->aaaaa,1->a,1->a;
如果想让这三部分回文串独立没有交集,那么三部分的字母换成各不相同的即可(例如:aaaaabc)

代码
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131 
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
//#define int long long
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps=1e-7;
const double pai=acos(-1.0);
const int N=2e4+10;
const int maxn=1e6+10;
const int mod=1e9+7;
int t,n,m,p[maxn]; 
void init()
{
	int sum=0;
	for(int i=1;i<=217;i++)
	{
		sum+=i;
		p[i]=sum;
	}
}
int main( )
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	init();
	cin>>t;
	while(t--)
	{
		string s;
		int cnt=0,pos=0;
		cin>>m;
		while(m)
		{
			for(int i=217;i>=1;i--)
			{
				if(p[i]<=m)
				{
					pos=i;
					break;
				}
			}
			m-=p[pos];
			for(int i=1;i<=pos;i++)
				s+=(char)('a'+cnt);
			cnt++;
		}
		cout<<s<<endl;
	}
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值