HDU 5578.Friendship of Frog【字符串相同字符最近距离】【2015ACM/ICPC亚洲区上海站】【12月30】

Friendship of Frog

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  2nd  frog, 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,代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//大水题!
int main()
{
    int T, kase = 1;
    cin >> T;
    while(T--)
    {
        char s[1100];
        int f[30];//保存上一次字母出现的位置
        memset(f, -1, sizeof(f));
        int ans = 1<<20;
        scanf("%s", s);
        int l = strlen(s);
        for(int i = 0;i < l; ++i)
        {
            if(f[s[i]-'a'] != -1 && i - (f[s[i]-'a']) < ans) ans = i - f[s[i]-'a'];
            f[s[i]-'a'] = i;
        }
        printf("Case #%d: ", kase++);
        if(ans == 1<<20) cout << -1 << endl;
        else cout << ans <<endl;
    }
    return 0;
}


你可能感兴趣的:(C++,ACM,HDU,上海)