HDU-5578 Friendship of Frog

Posted Kiven#5197

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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): 723

Problem Description
N 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 N1th 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.
 

 

Input
First 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.

 1T50.

 for 80% data, 1N100.

 for 100% data, 1N1000.

 the string only contains lowercase letters.
 

 

Output
For 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 Input
2
abcecba
abc
 
 
Sample Output
Case #1: 2
Case #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         else
27         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的主要内容,如果未能解决你的问题,请参考以下文章

What's friendship?

POJ 1815 Friendship

zoj2833Friendship

writing: friendship and growth

Friendship POJ - 1815 基本建图

writing: friendship and growth