一些只含0/1的串,判断是否有一个为另一个的前缀(相同不算)
方法一:字符串处理
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
char str[1010];
string s[1010];
int cmp (char *a, char *b) {
return strcmp(a, b);
}
int main() {
int N, i, j;
while (scanf("%d", &N) == 1 && N > 0) {
for (i = 0; i < N; i++) {
scanf("%s", str);
s[i] = str;
}
sort(s, s + N);
for (i = 1; i < N; i++) {
j = i - 1;
if (strncmp(s[i].c_str(), s[j].c_str(),
min(s[i].size(), s[j].size())) == 0
&& s[i].size() != s[j].size())
break;
}
if (i == N)
printf("None!\n");
else
printf("Exist!\n");
}
return 0;
}
方法二:二叉树(数组存储),感觉没有问题,wa了,求解
#include<stdio.h>
#include<string.h>
#include<iostream>
#define M 2<<12
using namespace std;
char s[M];
char b[16];
int flag;
void Insert()
{
int i;
char *p;
for(i=2,p=b;*p;i<<=1,p++){
if(s[i]==2){ flag=1;return ;}//遇到标识的串
if(*p=='0') s[i]=1;
else s[++i]=1;
}
if(s[i]==1) {flag=1;return ;}//此串为其他串的前缀
s[i]=2;//标识出此串
}
int main()
{
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int t;
while(cin>>t,t)
{
memset(s,0,sizeof(s));
flag=0;
getchar();
//int tmp=t;
while(t--)
{
gets(b);
//cout<<b<<endl;
if(!flag) Insert();
}
// cout<<tmp<<endl;
if(flag) cout<<"Exist!"<<endl;
else cout<<"None!"<<endl;
}
return 0;
}