0% found this document useful (0 votes)
19 views2 pages

HHFHHHF Notes

The code takes in a string, checks if all characters are the same, and if not, sorts the string and finds the next safe permutation up to 40320 iterations, printing the result. It completes this process for multiple test cases read from standard input.

Uploaded by

Shivam Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views2 pages

HHFHHHF Notes

The code takes in a string, checks if all characters are the same, and if not, sorts the string and finds the next safe permutation up to 40320 iterations, printing the result. It completes this process for multiple test cases read from standard input.

Uploaded by

Shivam Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <algorithm>
using namespace std;

bool safe(string s) {
string c = "codechef";
for (int i = 0; i < 8; i++) {
if (s[i] == c[i]) {
return false;
}
}
return true;
}

int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;

// Check if all characters in the input string are the same.


bool allSame = true;
for (int i = 1; i < s.length(); i++) {
if (s[i] != s[0]) {
allSame = false;
break;
}
}

if (allSame) {
cout << "-1" << endl;
continue; // Move on to the next test case.
}

if (!safe(s)) {
// Sort the characters of s to get the smallest possible permutation.
sort(s.begin(), s.end());

int cnt = 0;
// Find the first safe permutation of s, breaking after 40320
iterations.
while (next_permutation(s.begin(), s.end()) && cnt < 40320) {
if (safe(s)) {
break;
}
cnt++;
}

if (cnt >= 40320) {


cout << "-1" << endl;
continue; // Move on to the next test case.
}
}

cout << s << endl;


}
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;

bool safe(string s) {
string c = "codechef";
for (int i = 0; i < 8; i++) {
if (s[i] == c[i]) {
return false;
}
}
return true;
}

int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;

// Check if all characters in the input string are the same.


bool allSame = true;
for (int i = 1; i < s.length(); i++) {
if (s[i] != s[0]) {
allSame = false;
break;
}
}

if (allSame) {
cout << "-1" << endl;
continue; // Move on to the next test case.
}

if (!safe(s)) {
// Sort the characters of s to get the smallest possible permutation.
sort(s.begin(), s.end());

int cnt = 0;
// Find the first safe permutation of s, breaking after 40320
iterations.
while (next_permutation(s.begin(), s.end()) && cnt < 40320) {
if (safe(s)) {
break;
}
cnt++;
}

if (cnt >= 40320) {


cout << "-1" << endl;
continue; // Move on to the next test case.
}
}

cout << s << endl;


}
return 0;
}

You might also like