CodeForces 254C 字典序

Description

input
input.txt
output
output.txt

String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.

You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.

The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1p2 = q2, ..., pk - 1 = qk - 1pk < qk for some k (1 ≤ k ≤ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.

Input

The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1to 105 characters) and consist of uppercase English letters.

Output

In the first line print z — the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.

Sample Input

Input
ABA
CBA
Output
1
ABC
Input
CDBABC
ADCABD
Output
2
ADBADC

題意:輸入兩個長度相同的字符串s,t,要求對s進行最少的改動(每次替換一個字母)使s成爲t的重組字(字幕出現次序相同,不要求順序),如果存在多種改動情況,輸出最小字典序的那個。

思路:難點在於字典序,這裏引入一個鬆弛概念,如果s中剩餘x個D,而需要替換掉x個D,它是不鬆弛的,遇到D則一定要把它替換掉,而s中剩餘x個D,需要替換掉小於x個D,那麼它是鬆弛的,貪心思想,如果替換掉使s字典序變小,那就換,否則就不換。


#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<sstream>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
using namespace std;

int main(){
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	map<char,int> cnts,cnt;
	vector<char> ch;
	string s,t;
//    char s[10005],t[10005];
	cin>>s>>t;
	for(int i=0;i<s.size();i++){
		cnts[s[i]]++;
		cnt[s[i]]++;
	}
	for(int i=0;i<t.size();i++){
		cnt[t[i]]--;
	}
	int num=0;

	for(int i=0;i<s.size();i++){
		cnts[s[i]]--;
		if(cnt[s[i]]>0){//需替換 
			if(cnts[s[i]]+1<=cnt[s[i]]){ //不鬆弛,一定替換 
//			    printf("debug\n");
				for(char j='A';j<='Z';j++){
					if(cnt[j]<0){
						cnt[s[i]]--;
						s[i]=j;
						cnt[j]++;
						num++;
						break;
					}
				}
			
			}else{ //鬆弛,只替換使字典序變小的 
				for(int j='A';j<='Z';j++){
					if(j>s[i])
					  break;
					if(cnt[j]<0){
						cnt[s[i]]--;
						s[i]=j;
						cnt[j]++;
						num++;
						break;;
					}					
				}
			}
		}	
	}
	cout<<num<<"\n"<<s<<endl;
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章