[Title] thinking CodeForce 1009B Minimum Ternary String

Copyright: Johnson https://blog.csdn.net/m0_38055352/article/details/91294676

To indulge this time to brush the question for some time, let CSDN accompany me with it!

First, the title effect

It means that the subject contains only to a '0' string '1', '2', wherein you can neighboring '0' and '1' of the exchange, which also may be adjacent to '1' and '2' are exchanged, but can not exchange lexicographically smallest adjacent strings may be swapped out after the request of a given string of '0' and '2'.

Second, the subject of thinking and AC codes

This question is not considered first, then the time is violence solved, you only need to define the rules of correct exchange of ideas to do it by simulation questions, you can get the right answers, but note that the length of a given string is 1e5, violence then need to traverse many times string, if the data is not very water, it is very difficult to pass.

Then we will begin to find the law of the exchange of results, through analysis we can find the string after the exchange must be in the form of: 00 ... 0111 ... 0200 ... 11200 ... 0200.0200.00, what does it mean? Is a start after a given string, leading zeros is certainly not to be exchanged, then because 1 can be exchanged and all the strings, then all must be followed by 1 (One might wonder why hold back 0 in this, since the exchange can not be 0 and 2, so that only the back is blocked), then a is 2, since the exchange 2 and not 0, the 0 2 between the two or between two available 2 behind it is the case, after finding such a law, we only need one to start scanning again, the data we need to store it, and then look for the answer when it will be much faster! Substantially is O (n) complexity.

AC codes are given below:

#include <iostream>
#include <string>
#include <cstring>
#define MAX 100010
using namespace std;

string str;
int fTwo[MAX];
int nZero[MAX];
int nOne;

int main()
{
	cin >> str;
	int len = str.length();

	int size = 0;
	for (int i = 0; i < len; i++) {
		if (str[i] == '0') {
			nZero[size]++;
		}
		else if (str[i] == '1') {
			nOne++;
		}
		else {
			fTwo[size++] = i;
		}
	}

	string ans = "";
	ans += string(nZero[0], '0');
	ans += string(nOne, '1');
	if (size) {
		ans += '2';
		for (int i = 1; i < size; i++) {
			if (nZero[i]) {
				ans += string(nZero[i], '0');
			}
			ans += '2';
		}
		if (nZero[size]) ans += string(nZero[size], '0');
	}

	cout << ans << endl;

    return 0;
}

If you have questions, please correct me! ! !

Guess you like

Origin blog.csdn.net/m0_38055352/article/details/91294676