BUPT OJ|127.最小距离查询

题目来源 北邮OJ在这里插入图片描述
法一:最后的输出一定要用printf,cout会运行超时

#include<iostream>
#include<algorithm>
#include<cstring>
#include<limits.h>
#include<math.h>
#include<vector>
using namespace std;

int main()
{
	std::ios::sync_with_stdio(false);
	int T,N;
	char ch;
	string str,opt;
	cin>>T;
	while(T--){
		cin>>str;
		cin>>N;
		vector<vector<int> > a(27);
		for(int i=0,len=str.length();i<len;i++) {
            a[str[i]-'a'].push_back(i);
        }
		while(N--){
			cin>>opt;
			if(!opt.compare("INSERT")){
				cin>>ch;
				str.push_back(ch); 
				a[ch-'a'].push_back(str.length()-1);
			}else if(!opt.compare("QUERY")){
				int MIN=INT_MAX,x,siz;
				cin>>x;
				siz=a[str[x]-'a'].size();
				if(siz==1) printf("-1\n");
				else{
					for(int i=0;i<siz;i++){
						if(abs(a[str[x]-'a'][i]-x)<MIN&&abs(a[str[x]-'a'][i]-x)>0)
							MIN=abs(a[str[x]-'a'][i]-x);
					}
					printf("%d\n",MIN);//!!!!!
				}
			}
		}
	} 
}

法二:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<cstring>
#include<limits.h>
#include<math.h>
#include<vector>
using namespace std;

int main()
{
	int T,N;
	scanf("%d",&T);
	while(T--){
		char ch[2],str[100005],opt[20];
		vector<vector<int> > a(27);
		scanf("%s",str);
		scanf("%d",&N);
		for(int i=0,len=strlen(str);i<len;i++) {
            a[str[i]-'a'].push_back(i);
        }
		while(N--){
			scanf("%s",opt);
			if(strcmp(opt,"INSERT")==0){
				scanf("%s",&ch);
				strcat(str,ch);
				a[ch[0]-'a'].push_back(strlen(str)-1);
			}else if(strcmp(opt,"QUERY")==0){
				int x,siz,MIN=INT_MAX;
				scanf("%d",&x);
				siz=a[str[x]-'a'].size();
				if(siz==1) printf("-1\n");
				else{
					for(int i=0;i<siz;i++){
						if(abs(a[str[x]-'a'][i]-x)<MIN&&abs(a[str[x]-'a'][i]-x)>0)
							MIN=abs(a[str[x]-'a'][i]-x);
					}
					printf("%d\n",MIN);
				}
			}
		}
	} 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值