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;
}