hdu5578_Friendship of Frog_思維

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=5578


題目大意:讓你找出兩個相同字母間的最小距離。


解題思路:

對字母組進行標記,出現過的字母標記下,並記下位置,再次出現的時候計算一下與上一次距離,然後更新最小距離就行

代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
const int inf=0x3f3f3f3f;
int main()
{
    int t;
    int a[30],d[30],new1[30];
    char str[1005];
    scanf("%d",&t);
    int cas=0;
    while(t--)
    {
        int mnn=inf;
        memset(a,0,sizeof(a));
        memset(d,0,sizeof(d));
        memset(new1,0,sizeof(new1));
        scanf("%s",str);
        int len= strlen(str);
        for(int i=0;i<len;i++)
        {
            int tmp=str[i]-'a';
            if(!a[tmp])
            {
                a[tmp]=1;
            }
            else
            {
                d[tmp]=i-new1[tmp];
                mnn=min(mnn,d[tmp]);
            }
            new1[tmp]=i;
        }
        printf("Case #%d: ",++cas);
        if(mnn!=inf)
        printf("%d\n",mnn);
        else
        printf("-1\n");
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章