【codechef】Yet Another Problem On Strings (找最优解)

You are given a string X consisting of lowercase alphabets. You are required to generate the largest stringY from X by following the given instructions below:

  • frequency(Y[i]) in X >= frequency(Y[j]) in X, where 1<=j<=i-1 and frequency(c) in X denotes the the number of occurrences of the letter c in the string X.
  • ASCII(Y[i]) > ASCII(Y[j]), where 1<=j<=i-1.



If there are multiple such strings Y, then you are required to print the lexicographically smallest string among them.

Note: All strings are indexed from 1.

Input

  • The first line of the input contains an integer T denoting the number of test cases. The description of Ttest cases follows.
  • The first line of each test case contains a single string X

Output

  • For each test case, output a single line containing the string Y as described above.

Constraints

  • 1 ≤ T ≤ 1000
  • 1 ≤ Length of X ≤ 1000

Example

Input:
3
codejam
birlainstituteoftechnology
rrramu
Output:
acdejmo
abcfghlnot
amr

http://www.codechef.com/BTCJ2015/problems/BITCJ4

一道类似dp的题目,做法挺巧妙的。。

#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<queue>
#include<string.h>
#include<stdlib.h>
#include<stack>
#include<cstdio>
#define ll long long
using namespace std;
int main(){
	int t;
	cin>>t;
	while(t--){
		string x;
		cin>>x;
		int y[26]={0};
		int l[26];     //level
		int p[26];     //parent
		for(int i=0;i<26;++i){
			l[i]=1;
			p[i]=-1;
		}
		for(int i=0;i<x.length();++i){
			y[x[i]-'a']++;
		}
		int max=0,g=-1;
		for(int i=0;i<26;++i){
			for(int j=0;j<i;++j){
				if(y[i]>=y[j]&&l[i]<=l[j]&&y[i]>0&&y[j]>0){
					l[i]=l[j]+1;
					p[i]=j; 
				}
			}
			if(l[i]>max){
				max=l[i];
				g=i;
			}	
		}
		stack<int> sk; //因为要逆序数出 
		while(g!=-1){
			sk.push(g);
			g=p[g];
		}
		while(!sk.empty()){
			cout<<char(sk.top()+'a');
			sk.pop();
		}
		cout<<endl;
	}
	return 0;
}


你可能感兴趣的:(【codechef】Yet Another Problem On Strings (找最优解))