G-小明不希望太简单_2022河南萌新联赛第(七)场:南阳理工学院 (nowcoder.com)
题意:
思路:
每次都取字符串中出现次数最多的两个字符就好了
Code:
#include <bits/stdc++.h>
using namespace std;
string s,res;
unordered_map<char,int> mp;
priority_queue<pair<int,char> >q;
int main(){
res="";
getline(cin,s);
for(auto it:s) mp[it]++;
for(auto it:mp) q.push({it.second,it.first});
pair<int,char> p1,p2;
while(q.size()>1){
p1=q.top();q.pop();
p2=q.top();q.pop();
res+=p1.second;
res+=p2.second;
if(--p1.first>0) q.push({p1.first,p1.second});
if(--p2.first>0) q.push({p2.first,p2.second});
}
if(q.size()==1){
pair<int,char> p1=q.top();
res+=p1.second;
}
cout<<res;
}
总结:
思维:不会做的时候就观察一下特征,比如这道题就是观察相邻不重复的两个字符的特征,出现次数不同的字符一定不同
写法:
1.优先队列中如果是pair类型,那么优先队列会按pair类型的first作为排序的依据
2.可以用auto遍历map
细节:
unordered_map比map快,因为不需要排序,因此用unordered_map会更保险一点,否则可能超时