题目描述:
显然,这是一道处理字符串的题,用map即可
但是读入挺麻烦的
#include <bits/stdc++.h>
#include <map>
#include <cstring>
using namespace std;
map<string,int>mp;
int main(void){
string str;
getline(cin,str);
int len=str.size();
for(int i=0;i<len;++i){
int sum=0;
string ans="";
if(str[i]!=' '&&isdigit(str[i])==0){
while(str[i]!=' '&&isdigit(str[i])==0){
ans=ans+str[i];
i++;
}
}
if(str[i]==' ') i++;
while(isdigit(str[i])){
sum=sum*10+(str[i]-'0');
i++;
}
//cout<<ans<<sum<<"\n";
mp[ans]=mp[ans]+sum;
}
int n;
string ss;
cin>>n;
while(n--){
cin>>ss;
cout<<mp[ss]<<"\n";
}
return 0;
}
下面是在读入上进行优化的ac代码
#include <bits/stdc++.h>
using namespace std;
map<string, int>mp;
int main(void){
while(cin.peek()!='\n'){
string s;
int num;
cin>>s>>num;
mp[s]=mp[s]+num;
}
int n;
string str;
cin>>n;
while(n--){
cin>>str;
cout<<mp[str]<<"\n";
}
}