You are given a ternary string (it is a string which consists only of characters ‘0’, ‘1’ and ‘2’).
You can swap any two adjacent (consecutive) characters ‘0’ and ‘1’ (i.e. replace “01” with “10” or vice versa) or any two adjacent (consecutive) characters ‘1’ and ‘2’ (i.e. replace “12” with “21” or vice versa).
For example, for string “010210” we can perform the following moves:
“010210”
→
“100210”;
“010210”
→
“001210”;
“010210”
→
“010120”;
“010210”
→
“010201”.
Note than you cannot swap “02”
→
“20” and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String
a
is lexicographically less than string
b
(if strings
a
and
b
have the same length) if there exists some position
i
(
1
≤
i
≤
|
a
|
, where
|
s
|
is the length of the string
s
) such that for every
j
i
holds
a
j
b
j
, and
a
i
b
i
.
Input
The first line of the input contains the string
s
consisting only of characters ‘0’, ‘1’ and ‘2’, its length is between
1
and
10
5
(inclusive).
Output
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
inputCopy
100210
outputCopy
001120
inputCopy
11222121
outputCopy
11112222
inputCopy
20
outputCopy
20
看完题目之后第一反应是 贪心: 遇到 1,0 交换;遇到2 ,1也交换,因为要求字典序最小;
考虑这个反例: 2021
按照贪心思想:最后应该是 2012;其实更优解是 1202 .
那么贪心不成立:
考虑交换规律:
可以发现1可以与0,2互换,也就是说1可以自由移动,所以我们先统计有几个1,然后置于开头,必然会形成如下字符串:
1111111……000000……2022000….
后面是0,2的随意组合;
自然0应该是越往前越好;
所以可以得到:
00000000…..1111111….02022200…..
后面是0,2的原排列;
因此:
① 统计有多少个1;
② 统计第一个2之前的所有0;
③第一个2 之后2与0的原排列;
最后按照213输出即可;
#include
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define maxn 200005
const int mod=1e9+7;
#define eps 1e-5
#define pi acos(-1.0)
ll quickpow(ll a,ll b)
{
ll ans=1;
while(b){
if(b&1){
ans=ans*a;
}
a=a*a;
b>>=1;
}
return ans;
}
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
//char cc[maxn];
int main()
{
ios::sync_with_stdio(false);
string ch,ch1,ch2,ch3;
cin>>ch;
int len=ch.length();
int flag=0;
int i,j;
for(i=0;i
上面代码会 tle ;改用 char 即可
#include
using namespace std;
#define maxn 200005
typedef long long ll;
#define inf 0x3f3f3f3f
#define eps 1e-5
const long long int mod=1e9+7;
char ch[maxn];
char ss1[maxn],ss2[maxn],ss3[maxn];
int main(){
ios::sync_with_stdio(false);
cin>>ch;
int flag=0;
int i,j;
int x=0,y=0,z=0;
int len=strlen(ch);
for(i=0;i
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net