题意:替换字母为数字,使得和最小。替换的数字不能有前导零。
解题思路:简单的贪心,最长的那个字符串的第一个字母肯定设为1.这样肯定是不行的。因为有可能次短的数量有很多,因此要设置一个权重。计算每一个字母的权重,然后按照权重设置数字,其中要注意前导零。判断下就好了。
#include <iostream>
#include <deque>
#include <stdio.h>
#include <map>
#include <string.h>
#include <algorithm>
#include <vector>
#include <math.h>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long int ll;
string a[1005];
vector<vector<string> > list(6);
int main(){
int N;
cin>>N;
map<char,int> w;//记录权重
map<char,int> nozero;//记录不能设置为0的字母
for(int i=0;i<N;i++){
cin>>a[i];
list[a[i].size()-1].push_back(a[i]);
for(int j=0;j<a[i].size();j++)
w[a[i][j]]+=pow(10,a[i].size()-j-1);//计算权重
nozero[a[i][0]]=1;
}
vector<pair<int,char> > s;
for(int i=0;i<10;i++)
if(w['a'+i]!=0)
s.push_back(make_pair(w['a'+i],'a'+i));//对权重排个序
sort(s.begin(),s.end());
map<char,int> r;//替换的数字
bool setz=1;
int num=1;
for(int i=s.size()-1;i>=0;i--){
//特判前导0
if(nozero[s[i].second]==0&&setz==1){
r[s[i].second]=0;
setz=0;
continue;
}
r[s[i].second]=num;
num++;
}
int sum=0;
for(int i=0;i<N;i++){
for(int j=0;j<a[i].size();j++)
a[i][j]='0'+r[a[i][j]];//替换
// cout<<a[i]<<endl;
sum+=stoi(a[i]);
}
cout<<sum<<endl;
return 0;
}