CodeForces - 794C:Naming Company(博弈&簡單貪心)
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.
To settle this problem, they‘ve decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n
For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :
Initially, the company name is ???.
Oleg replaces the second question mark with ‘i‘. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.
Igor replaces the third question mark with ‘o‘. The company name becomes ?io. The set of letters Igor have now is {i, m}.
Finally, Oleg replaces the first question mark with ‘o‘. The company name becomes oio. The set of letters Oleg have now is {i}.
In the end, the company name is oio.
Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?
A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm(where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tjfor all j < i)
Input
The first line of input contains a string s of length n (1 ≤ n ≤ 3·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially.
The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.
Output
The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.
Examples
InputtinkoffOutput
zscoder
fzfsirkInput
xxxxxxOutput
xxxxxx
xxxxxxInput
ioiOutput
imo
ioi
題意:A,B都有N個字符,A和B輪流貢獻一個字符,A想組成的字典序越小,B想組成的字典序越大。
思路:A肯定是貢獻出最小的(N+1)/2個字符,B貢獻出最大的N/2個字符。 錯誤思路是A從小到大貢獻字符,B從大到小貢獻字符,但是會出現錯誤,
比如A=cbxy,B=aaaa,錯誤解=baca,正解=abac。正確的貪心策略應該是:對A,如果最小值小於B的最大值,那麽把最小值填到前面,否則把最大值填到最後。B同理。
#include<bits/stdc++.h> using namespace std; const int maxn=1000010; char a[maxn],b[maxn],ans[maxn]; int main() { int N,L,R,h1,t1,h2,t2; scanf("%s%s",a+1,b+1); N=strlen(a+1); sort(a+1,a+N+1); sort(b+1,b+N+1); L=1; R=N; h1=1; t1=(N+1)/2; h2=N; t2=N-N/2+1; while(L<=R){ if(a[h1]<b[h2]) ans[L++]=a[h1++]; else ans[R--]=a[t1--]; if(L>R) break; if(b[h2]>a[h1]) ans[L++]=b[h2--]; else ans[R--]=b[t2++]; } for(int i=1;i<=N;i++) printf("%c",ans[i]); return 0; }
CodeForces - 794C:Naming Company(博弈&簡單貪心)