HDU-5578-Friendship of Frog【2015上海赛区】

HDU-5578-Friendship of Frog

        Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

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

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.

⋅ 1≤T≤50.

⋅ for 80% data, 1≤N≤100.

⋅ for 100% data, 1≤N≤1000.

⋅ 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

题目链接:HDU-5578

题目大意:每个国家有一个字母编号,有n只青蛙来自不同的国家站成一条线上。相邻两只青蛙距离为1,属于同一个国家的为朋友。求最近的一对朋友距离为多少?

题目思路:用邻接链表存图。以26个字母为表头。遍历每个字母都有哪些位置,求出最近距离。

以下是代码:

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;

#define INF 0x3f3f3f3f
int main(){
    int t;
    scanf("%d",&t);
    int cas = 1;
    while(t--)
    {
        vector <int> g[30];
        string s;
        cin >> s;
        for (int i = 0; i < s.size(); i++)
        {       
            g[s[i] - 'a'].push_back(i);
        }
        int ans = INF;
        for (int i = 0; i < 26; i++)
        {
            if (g[i].size() < 2) continue;
            for (int j = 0; j < g[i].size() - 1; j++)
            {
                ans = min(ans,g[i][j + 1] - g[i][j]);
            }
        }
        if (ans == INF) ans = -1; 
        printf("Case #%d: %d\n",cas++,ans);
    }
    return 0;
}

你可能感兴趣的:(HDU-5578,2015上海)