2019 JUST Programming Contest E. Building Strings

E. Building Strings

题目链接-E. Building Strings
在这里插入图片描述
在这里插入图片描述
题目大意
长度为 n n n的字符串 s s s,该字符串由小写英文字母组成, s s s中每个字母的成本由长度为 n n n的另一个字符串c给出,该字符串由数字组成,表示使用字母 s i si si的成本是 c i ci ci硬币,给你一个长度为 m m m的字符串 p p p,该字符串由唯一的小写英文字母组成求使用 s s s的字母来构建字符串 p p p的最小成本

解题思路

  • 因为字符串 s s s中可能有重复的字母,相同的字母对应的成本不一定一样,而我们要求最小成本,所以我们可以遍历字符串 s s s c c c m a p map map存一下每个字母的最小成本
  • 记得用 m a p map map要初始化为 − 1 -1 1,用来后续判断 s s s中是否有相应字母
  • 然后遍历字符串 p p p,用ans+=mp[c[i]]记录成本,若mp[p[i]]==-1,则说明 s s s中没有相应字母 p [ i ] p[i] p[i],直接将 a n s ans ans置为 − 1 -1 1,跳出循环
  • 最后输出 a n s ans ans即可,具体操作见代码

附上代码

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double e=exp(1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=2e5+10;
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long ull;
string a,b,c;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);

	int t;
	cin>>t;
	while(t--){
		bool ass=0;
		int n,m,ans=0;
		cin>>n>>m;
		cin>>a>>b>>c;
		map<char,int> mp;
		for(int i=0;i<26;i++)
			mp[i+'a']=-1;
		for(int i=0;i<n;i++){
			if(mp[a[i]]==-1||mp[a[i]]>b[i]-'0')
				mp[a[i]]=b[i]-'0';
		}
		for(int i=0;i<m;i++){
			if(mp[c[i]]==-1){
				ans=-1;
				break;
			}
			ans+=mp[c[i]];
		}
		cout<<ans<<endl;
	} 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值