BUPT OJ 最小距離查詢

用了類似鄰接表的結構,一個vector,存放每種字母對應的出現位置,並在插入時排序。

用cin超時,scanf通過。。。

 怪不得連題目描述裏都強行提示最好用scanf。。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<vector>
#include<algorithm>
#define MAXSIZE 100001
using namespace std;
class node
{
    public:
        vector<int>link;
     
};
char str[MAXSIZE];
 
int main()
{
    int t,m,length;
    char insert_char[2];
    int query_int;
    char choice[7];
    scanf("%d",&t);
     
    while(t--)
    {
        node Node[26];
        //memset(Node,0,sizeof(Node));
        length=0;
        scanf("%s",str);
        length=strlen(str);
        for(int i=0;i<length;i++)
        {
             
            Node[str[i]-'a'].link.push_back(i);
         
             
        }
        scanf(" %d",&m);
        while(m--)
        {
            scanf("%s",choice);
            if(choice[0]=='I')
            {
                 
                scanf("%s",insert_char);
                str[length]=insert_char[0];
                (Node[insert_char[0]-'a']).link.push_back(length);
                sort(Node[insert_char[0]-'a'].link.begin(),Node[insert_char[0]-'a'].link.end());
                length++;
             
            }
             
            else{
                 
                int pos=0;
                int result=2000000;
                scanf("%d",&query_int);
                int temp=str[query_int]-'a';
                    int size=Node[temp].link.size();
                if(size>1){
             
                for(int i=0;i<size;i++)
                {
                 
                if(Node[temp].link[i]==query_int){
                pos=i;
         
                break;
                }
                 
                 
                }
                    if(pos-1>=0)result=min(result,abs(Node[temp].link[pos]-Node[temp].link[pos-1]));            
                    if(pos+1<size)result=min(result,abs(Node[temp].link[pos+1]-Node[temp].link[pos]));
                //  cout<<pos<<endl;
                printf("%d\n",result);
                        }
                else printf("-1\n");
            }
        }
         
    }
}

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