首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【zzuliOJ】1901 - 985的SS串难题(字典树 & dfs)

【zzuliOJ】1901 - 985的SS串难题(字典树 & dfs)

作者头像
FishWang
发布2025-08-27 09:53:26
发布2025-08-27 09:53:26
14200
代码可运行
举报
运行总次数:0
代码可运行

点击打开题目

1901: 985的SS串难题

Time Limit: 3 Sec Memory Limit: 128 MB Submit: 48 Solved: 5 Submit Status Web Board

Description

985定义一个串是SS串的条件是:串中不同字符个数为平方数或者平方数的2倍。现在他给你一个字符串,要求你按字典序输出所有不相同的SS子串。

(1 4 9 16 25 36...)

(2 8 18 32 50 72...)

Input

第一行输入一个整数t,代表有t组测试数据。每组数据输入一个字符串str。

注:1 <= t <= 10,1 <= |str| <= 1000,保证str里面只有小写字母。

Output

按字典序输出所有不相同的SS串。

Sample Input

1

abc

Sample Output

a

ab

b

bc

c

HINT

Source

hpu

把字符串的每一个子串(都到结尾)放到字典树里,并记录到当前为止不同字符的个数。

然后跑一遍dfs用STL - string类型记录结果,找到符合的就输出就行了。

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define idx(x) (x-'a')
int dic[8]={1,4,9,16,25,2,8,18};
struct Trie
{
	Trie *next[26];
	int v;
	void clear()
	{
		v = 0;
		for (int i = 0 ; i < 26 ; i++)
			next[i] = NULL;
	}
}tree[1000000];
int ant;
string ans;
bool check(int x)
{
	for (int i = 0 ; i < 8 ; i++)
		if (x == dic[i])
			return true;
	return false;
}
void insert(char *s)
{
	int l = strlen(s);
	Trie *p = &tree[0] , *q;
	int used[26];
	CLR(used,false);
	for (int i = 0 ; i < l ; i++)
	{
		int id = idx(s[i]);
		if (p->next[id] == NULL)
		{
			q = &tree[ant++];
			q->v = p->v;
			p->next[id] = q;
			if (!used[id])
				q->v++;
		}
		used[id] = true;		//应该在这里标记,如果在上面会漏掉某些串 
		p = p->next[id];
	}
}
void bfs(Trie *root)
{
	for (int i = 0 ; i < 26 ; i++)
	{
		if (root->next[i] != NULL)
		{
			ans += ('a' + i);
			if (check(root->next[i]->v))
//				cout << ans << endl;
				printf ("%s\n",ans.c_str());
			bfs(root->next[i]);
//			ans.erase(ans.end()-1);
			ans = ans.substr(0,ans.length()-1);
		}
	}
}
void del(int n)
{
	for (int i = 1 ; i < n ; i++)
		tree[i].clear();
}
int main()
{
	int u;
	char s[1011];
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%s",s);
		ant = 1;
		tree[0].clear();
		int l = strlen(s);
		char t[1011];
		for (int i = 0 ; i < l ; i++)
		{
			strcpy(t,s+i);
			insert(t);
		}
		ans = "";
		bfs(&tree[0]);
		del(ant);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-08-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1901: 985的SS串难题
  • Description
  • Input
  • Output
  • Sample Input
  • Sample Output
  • HINT
  • Source
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档