Surprising Strings
Description The D-pairs of a string of letters are the ordered pairs of letters that are distance D from each other. A string is D-unique if all of its D-pairs are different. A string is surprising if it is D-unique for every possible distance D. Consider the string ZGBG. Its 0-pairs are ZG, GB, and BG. Since these three pairs are all different, ZGBG is 0-unique. Similarly, the 1-pairs of ZGBG are ZB and GG, and since these two pairs are different, ZGBG is 1-unique. Finally, the only 2-pair of ZGBG is ZG, so ZGBG is 2-unique. Thus ZGBG is surprising. (Note that the fact that ZG is both a 0-pair and a 2-pair of ZGBG is irrelevant, because 0 and 2 are different distances.) Acknowledgement: This problem is inspired by the "Puzzling Adventures" column in the December 2003 issue of Scientific American. Input The input consists of one or more nonempty strings of at most 79 uppercase letters, each string on a line by itself, followed by a line containing only an asterisk that signals the end of the input. Output For each string of letters, output whether or not it is surprising using the exact output format shown below. Sample Input ZGBG X EE AAB AABA AABB BCBABCC * Sample Output ZGBG is surprising. X is surprising. EE is surprising. AAB is surprising. AABA is surprising. AABB is NOT surprising. BCBABCC is NOT surprising. Source |
irrelevant 不相关的 Acknowledgement 鸣谢,致谢;承认 asterisk 星号
思路:题目里的例子说的很清楚了——把母串根据字母间的距离分成多个字母对,判断相同距离中是否有相同的字母对,不存在为surprising string
输入以*结束
首先来说,输入限制是79个大写字母。如果暴力解决,应该也没问题
题目属于STL中的,对应的可以想到map
暴力:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
const int mod=100007;
using namespace std;
char s[100];
int ans(){
int l,d,i,j;
l=strlen(s);
if(l<3)
return 1;
d=1;
while(d<l){
for(i=0;i<l-d;i++){
for(j=i+1;j<l-d;j++){
if(s[i]==s[j]&&s[i+d]==s[j+d])
return 0;
}
}
d++;
}
return 1;
}
int main(){
while(scanf("%s",s)){
if(s[0]=='*')
return 0;
if(ans())
printf("%s is surprising.\n");
else
printf("%s is NOT surprising.\n");
}
return 0;
}
map(转载):
#include<iostream>
#include<cstring>
#include<map>
using namespace std;
int main()
{
char s[80];
while(cin>>s && s[0]!='*')
{
int len=strlen(s);
if(len<=2) //长度小于等于2的串必定是surprising String
{
cout<<s<<" is surprising."<<endl;
continue;
}
bool mark=true; //标记s是否为Surprising String
for(int d=0;d<=len-2;d++) //d为当前所选取的两个字母之间的距离,d(max)=len-2
{
map<string,bool>flag;
bool sign=true; //标记D-pairs字母对是不是D-unique
for(int i=0;i<=len-d-2;i++) //i为所选取的两个字母中第一个字母的下标
{
char pair[3]={s[i],s[i+d+1],'\0'}; //构成D-pairs字母对
if(!flag[ pair ])
flag[ pair ]=true;
else
{
sign=false; //存在相同的D-pairs,该字母对不是D-unique
break;
}
}
if(!sign)
{
mark=false; //存在非D-unique,s不是Surprising String
break;
}
}
if(mark)
cout<<s<<" is surprising."<<endl;
else
cout<<s<<" is NOT surprising."<<endl;
}
return 0;
}