2019HDU多校第一场 1009 String

166 篇文章 0 订阅

Problem Description

Tom has a string containing only lowercase letters. He wants to choose a subsequence of the string whose length is k and lexicographical order is the smallest. It's simple and he solved it with ease.
But Jerry, who likes to play with Tom, tells him that if he is able to find a lexicographically smallest subsequence satisfying following 26 constraints, he will not cause Tom trouble any more.
The constraints are: the number of occurrences of the ith letter from a to z (indexed from 1 to 26) must in [Li,Ri].
Tom gets dizzy, so he asks you for help.

 

 

Input

The input contains multiple test cases. Process until the end of file.
Each test case starts with a single line containing a string S(|S|≤105)and an integer k(1≤k≤|S|).
Then 26 lines follow, each line two numbers Li,Ri(0≤Li≤Ri≤|S|). 
It's guaranteed that S consists of only lowercase letters, and ∑|S|≤3×105.

 

 

Output

Output the answer string.
If it doesn't exist, output −1.

 

 

Sample Input

 

aaabbb 3 0 3 2 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

 

题意:给一个母串,给出每个字符出现次数的上下限,求长度为K的、满足次数要求的子串

思路:一位一位的求答案串,对每一位添加上去之后,判断剩下的串能不能满足条件

#include<vector>
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int M=1e5+50;
int k,n,cnt[M][50],last,ans,l[M],used[M],r[M];
char s[M],res[M];
vector<int> g[26];
int main(){
	while(scanf("%s%d",s,&k)!=EOF){
		memset(used,0,sizeof(used));
		for(int i=0;i<26;i++){
			scanf("%d%d",l+i,r+i);
			g[i].clear();
		}
		n=strlen(s);
		for(int i=0;i<=n+1;i++)for(int j=0;j<26;j++)cnt[i][j]=0;
		for(int i=n-1;i>=0;i--)for(int j=0;j<26;j++)cnt[i][j]=cnt[i+1][j]+(s[i]=='a'+j);
		for(int i=0;i<n;i++)g[s[i]-'a'].push_back(i);
		vector<int>::iterator head[26];
		for(int i=0;i<26;i++)head[i]=g[i].begin();
		ans=last=-1;	
		
		for(int i=0;i<k;i++){
			int f1=0;
			for(int j=0;j<26;j++){
				if(used[j]==r[j])continue;
				while(head[j]!=g[j].end()&&(*head[j])<=last)head[j]++;
				if(head[j]==g[j].end())continue;
				used[j]++;
				int pos=*head[j],sum1=0,sum2=0,flag=1;
				for(int t=0;t<26;t++){
					if(cnt[pos+1][t]+used[t]<l[t])flag=0;
					sum1+=max(l[t]-used[t],0);
					sum2+=min(cnt[pos+1][t],r[t]-used[t]); 
				}
				if(sum1>k-i-1||sum2<k-i-1)flag=0;
				if(!flag)used[j]--;
				else{
					res[i]='a'+j;
					f1=1;
					last=pos;
					break;
				}
			}
			if(!f1){
				printf("-1\n");		
				ans=1;
				break;
			}
		}
		if(ans==-1){//如果有答案 
			res[k]=0;
			printf("%s\n",res);
		}
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值