您的位置:首页 > 其它

poj3630-tire

2013-06-17 20:30 113 查看
题目连接

如果是TLE那就是分配内存超时了,动态分配就有行不通了。

所以这题要静态分配内存。

但这题让我RE很多次了,不知道什么原因,最后看到别人的代码,又没发现什么数据问题。后来才知道,每次访问结束后要释放内存。

这又让我加深对c++中类的构造函数和析构函数的理解。确实佩服c++的优点。

#include<cstdio>
//#include<iostream>
#include<cstring>
using namespace std;

struct node{
int flag;
node *next[10];
}Node[100000];

int cnt;
class Tire{ //声明为类,主要是要用到析构函数,及时释放内存
node root;
public:
Tire(){root=Node[0];} //构造函数
// ~Tire(){cout<<"called";}//里面的是作测试用的,这个写与不写没区别(但这个很重要,如果不是类,提交就RE了)系统会自动调用析构函数。
bool insert(char *ch)
{
int i=0;
node *tmp=&root;
int len=strlen(ch);
while(ch[i]){
int pos=ch[i]-'0';
if(i==len-1&&tmp->next[pos]!=0) return false;
if(tmp->next[pos]==0){
tmp->next[pos]=&Node[cnt];
Node[cnt].flag=0;
memset(Node[cnt].next,0,sizeof(Node[cnt].next));
cnt++;
}
if(tmp->next[pos]->flag==1) return false;
tmp=tmp->next[pos];
i++;
}
tmp->flag=1;
return true;
}
};

int main()
{
int t,n,ans;
char str[11];
scanf("%d",&t);
while(t--){
cnt=1;
Tire T;
scanf("%d",&n);
ans=1;
while(n--){
scanf("%s",str);
if(!T.insert(str)) ans=0;
}
if(ans) puts("YES");
else puts("NO");
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tire