首页 技术 正文
技术 2022年11月8日
0 收藏 406 点赞 1,479 浏览 1477 个字

题目http://acm.hdu.edu.cn/showproblem.php?pid=1671

题目本身不难,一棵前缀树OK,但是前两次提交都没有成功。

第一次Memory Limit Exceeded:

前缀树是很费空间的数据结构,每个节点存放了字母(数字)个数个指针,正所谓用空间来换取时间。

我发现我忘记写析构函数了,所以测例多起来还不释放很容易超空间。

树形结构的析构也很有趣:

 ~Node()
{
for (int i = ; i < ; ++i)
{
if (children[i])
{
delete children[i];
children[i] = nullptr;
}
}
}

好了,第二次没成功,Time Limit Exceeded:

看起来这是一棵规规矩矩的前缀树,仔细找可以优化的地方,试探性地把

 vector<Node *> children;
Node()
{
for (int i = ; i < ; ++i) children.push_back(nullptr);
}

改成了

 vector<Node *> children = vector<Node *>(, nullptr);
Node()
{
//for (int i = 0; i < 10; ++i) children.push_back(nullptr);
}

Accepted!显然构造的时候赋值比构造之后再赋值要快。。果然还是要尽可能的优化啊!

附代码:

 #include <string>
#include <vector>
#include <iostream> using namespace std; class Node
{
public:
bool is_phone = false;
vector<Node *> children = vector<Node *>(, nullptr);
Node()
{}
~Node()
{
for (int i = ; i < ; ++i)
{
if (children[i])
{
delete children[i];
children[i] = nullptr;
}
}
}
void insert(const string &_Phone)
{
Node *p = this;
for (int i = ; i < _Phone.size(); ++i)
{
int curr = _Phone[i] - '';
if (p->children[curr] == nullptr)
{
p->children[curr] = new Node();
}
p = p->children[curr];
}
p->is_phone = true;
}
bool has_phone(const string &_Phone)
{
Node *p = this;
for (int i = ; i < _Phone.size(); ++i)
{
int curr = _Phone[i] - '';
if (!p->children[curr]) return false;
if (p->children[curr]->is_phone) return true;
p = p->children[curr];
}
return true;
}
}; typedef Node *Trie; int main()
{
int t;
cin >> t;
while (t--)
{
Trie trie = new Node();
int n;
cin >> n;
string phone;
bool flag = true;
while (n--)
{
cin >> phone;
if (trie->has_phone(phone)) { flag = false; }
trie->insert(phone);
}
if (flag) cout << "YES" << endl;
else cout << "NO" << endl;
delete trie;
}
//system("pause");
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849