BIT_201906【D - Xiao Ming's String】

Ideas:

  • The number of each character and its deposit into a structure ALPHA , each priority queue is taken up two printing characters. Note that the last successful determination conditions.

Code:

  • 46ms 400KB
#include <iostream>
#include <cstring>
#include <string>
#include <queue>

using namespace std;

string str , ans;
struct ALPHA{
	char c;
	int cnt;
	ALPHA(char _c , int _cnt) : c(_c) , cnt(_cnt) {} ;
	friend bool operator < (const ALPHA &a , const ALPHA &b)
	{
		return a.cnt < b.cnt ;
	}
};
priority_queue <ALPHA , vector<ALPHA> , less<ALPHA> > Q;
int num[30];

int main(){
	cin>>str;
	memset(num , 0 , sizeof(num));
	for(int i=0 ; i<str.size() ; i++)
		num[str[i] - 'a']++;
	for(int i=0;i<26;i++)
		Q.push(ALPHA(char('a' + i) , num[i]));
	while(Q.size()){
		ALPHA L = Q.top() ; Q.pop() ;
		if(!L.cnt) break;
		ans += L.c ; L.cnt-- ;
		
		ALPHA R = Q.top() ; Q.pop() ;
		Q.push(L) ;
		if(!R.cnt) break;
		ans += R.c ; R.cnt-- ;
		Q.push(R) ;
	}
	ALPHA cur = Q.top() ; Q.pop() ;
	bool ok = true;
	if(cur.cnt > 1)
		ok = false;
	for(int i=1 ; i < ans.size() ; i++){
		if(ans[i] == ans[i-1]){
			ok = false;
			break;
		}
	}
	if(ok)
		cout<<ans<<endl;
	else
		cout<<"NO"<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/flash403/article/details/94147694