首页 > 代码库 > HDU-5578 Friendship of Frog
HDU-5578 Friendship of Frog
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1134 Accepted Submission(s): 723Problem DescriptionN frogs from different countries are standing in a line. Each country is represented by a lowercase letter. The distance between adjacent frogs (e.g. the 1st and the 2ndfrog, the N−1th and the Nth frog, etc) are exactly 1. Two frogs are friends if they come from the same country.
The closest friends are a pair of friends with the minimum distance. Help us find that distance.
InputFirst line contains an integer T, which indicates the number of test cases.
Every test case only contains a string with length N, and the ith character of the string indicates the country of ith frogs.
⋅ 1≤T≤50.
⋅ for 80% data, 1≤N≤100.
⋅ for 100% data, 1≤N≤1000.
⋅ the string only contains lowercase letters.
OutputFor every test case, you should output "Case #x: y", where x indicates the case number and counts from 1 and y is the result. If there are no frogs in same country, output −1 instead.
Sample Input2abcecbaabcSample OutputCase #1: 2Case #2: -1
题意:
有不同国家的蛤,求相同国家相邻最近的两个蛤的距离,没有相等就输出-1.
上海的题,上海的题吧,果然是上海的题吧!!
共有26个字母 所以只要每一位向上比较26位就好了,最先出现的哦哦诶就是当前元素的最小值,注意不要越界。
附AC代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 const int INF=1<<30; 5 6 7 int main(){ 8 int t; 9 cin>>t;10 int ans=1;11 while(t--){12 string s;13 cin>>s;14 int len=s.size();15 int MIN=INF;16 for(int i=0;i<len;i++){17 for(int j=1;j<=26&&i+j<len;j++){18 if(s[i]==s[i+j]){19 MIN=min(MIN,j);20 break;21 }22 }23 }24 if(MIN==INF)25 cout<<"Case #"<<ans++<<": -1"<<endl;26 else27 cout<<"Case #"<<ans++<<": "<<MIN<<endl;28 }29 return 0;30 }
看到有大神用字符转换做,给跪:
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 using namespace std; 5 char s[1010]; 6 int a[30]; 7 int main() 8 { 9 int t,T=1,i,l;10 scanf("%d",&t);11 while(t--)12 {13 memset(a,-1,sizeof(a));14 scanf("%s",s);15 l=strlen(s);16 int ans=0x3f3f3f;17 for(i=0;i<l;i++)18 {19 if(a[s[i]-‘a‘]!=-1)20 ans=min(ans,i-a[s[i]-‘a‘]);21 a[s[i]-‘a‘]=i;22 }23 if(ans==0x3f3f3f)24 ans=-1;25 printf("Case #%d: %d\n",T++,ans);26 }27 return 0;28 }
HDU-5578 Friendship of Frog
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。