您的位置:首页 > 其它

kuangbin kmp专题中的字符串暴力

2016-02-21 20:48 274 查看
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=70325#overview

M.

题意:T组数据,每组n个字符串,求他们共同的最大子串,使每个字符串都包含该串或者该串的逆。输出子串的最大长度

做法:找出最短串的坐标,枚举最短串的所有子串,及枚举从不同位置开始的不同长度的全部子串。利用strstr(母串,子串)函数,判断是否包含子串。

//枚举最短字符串的全部子串。strstr和kmp功能时间类似返回NULL表示没有该子串
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char s[105][105];
char t[105],it[105];
void inverse()
{
int l = strlen(t);
for(int i = 0; i < l; i ++)
{
it[i] = t[l - 1- i];
}
it[l] = '\0';
//cout<<it<<endl;
}
int main()
{
//   freopen("in.txt","r",stdin);
int T,n;
scanf("%d",&T);
while(T--)
{
int minx = 105,l,p = 0;
scanf("%d",&n);
for(int i = 0; i < n; i ++)
{
scanf("%s",s[i]);
l = strlen(s[i]);
if(l < minx)
{
p = i;
minx = l;
}
}
bool flag = false;
int ans = 0;
for(int i = 0;i < minx; i ++)
{
for(int j = 1; j <= minx - i; j ++)
{
//cout<<j;
strncpy(t,s[p] + i,j);
t[j] = '\0';
// cout<<t<<endl;
inverse();
flag = false;
for(int k = 0;k < n; k ++)
{
if(strstr(s[k],t) == NULL && strstr(s[k],it) == NULL)
{
flag = true;
break;
}
}
if(flag == false)
{
//cout<<t<<endl;
//cout<<it<<endl;
//cout<<i<<j<<ans<<endl;
ans = max(ans,j);
}
}
}
printf("%d\n",ans);
}
return 0;
}


N.

题意: 每组数据给n个字符串,求他们共同的最大子串。输出子串的长度,如果子串长度小于1,按题目要求输出

做法:找出最短串的坐标,枚举最短串的所有子串,及枚举从不同位置开始的不同长度的全部子串。利用strstr(母串,子串)函数,判断是否包含子串。

//枚举最短字符串的全部子串。strstr和kmp功能时间类似返回NULL表示没有该子串
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char s[4002][205];
char t[205],c[205];
int main()
{
//freopen("in.txt","r",stdin);
int n;
while(1)
{
int minx = 205,l,p = 0;
scanf("%d",&n);
if(n == 0)
{
break;
}
for(int i = 0; i < n; i ++)
{
scanf("%s",s[i]);
l = strlen(s[i]);
if(l < minx)
{
p = i;
minx = l;
}
}
bool flag = false;
int ans = 0;
for(int i = 0;i < minx; i ++)
{
for(int j = 1; j <= minx - i; j ++)
{
// cout<<j<<endl;
strncpy(t,s[p] + i,j);
t[j] = '\0';
// cout<<t<<endl;
flag = false;
for(int k = 0;k < n; k ++)
{
if(strstr(s[k],t) == NULL)
{
flag = true;
break;
}
}
if(flag == false)
{
if(ans < j)
{
ans = j;
strcpy(c,t);
}
else if(ans == j)
{
if(strcmp(c,t) > 0)
{
strcpy(c,t);
}
}
}
}
}
// cout<<ans<<endl;
if(ans != 0)
printf("%s\n",c);
else
printf("IDENTITY LOST\n");
}
return 0;
}

Y.

题意:题干很长,其实都没用。只是简单的求给出的文章中doge出现的次数,doge不分大小写

做法:直接读取,判断是否有doge

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
string s;
int main()
{
//freopen("in.txt","r",stdin);
int ans = 0;
while(cin>>s)
{

int n = s.size();
for(int i = 0;  i < 3; i ++)//先对前三个字符处理
{
if(s[i] >= 'A' && s[i] <= 'Z')
{
s[i] += 32;
}
}
for(int i = 0; i < n - 3; i ++)
{
if(s[i + 3] >= 'A' && s[i + 3] <= 'Z')
{
s[i + 3] += 32;
}

if(s[i] == 'd' &&s[i + 1] == 'o'&&s[i + 2] == 'g' && s[i + 3] == 'e' )
{
ans ++;
}
}

}
cout<<ans<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 字符串 暴力 水题