Reorganice la string dada de modo que todos los índices múltiples primos tengan el mismo carácter

Dada una string str de tamaño N . La tarea es averiguar si es posible reorganizar los caracteres en la string str de modo que para cualquier número primo p <= N y para cualquier número entero i que varíe de 1 a N/p, se debe cumplir la condición str p = str p*i . Si no es posible realizar tal reordenamiento, imprima -1. Ejemplos:

Entrada: str = “aabaaaa” Salida: baaaaaa El tamaño de la string es 7. Los índices 2, 4, 6 contienen el mismo carácter. Los índices 3, 6 contienen el mismo carácter. Entrada: str = “abcd” Salida: -1

Acercarse:

  • Todas las posiciones excepto la primera y aquellas cuyo número sea primo mayor N/2 deben tener el mismo símbolo.
  • Las posiciones restantes pueden tener cualquier símbolo. Estas posiciones se mantuvieron utilizando el tamiz .
  • Si el elemento más ocurrido en la string es menor que estas posiciones, imprima -1.

A continuación se muestra la implementación del enfoque anterior: 

C++

// CPP program to rearrange the given
// string such that all prime multiple
// indexes have same character
#include <bits/stdc++.h>
using namespace std;
#define N 100005
 
// To store answer
char ans[N];
int sieve[N];
 
// Function to rearrange the given string
// such that all prime multiple indexes
// have the same character.
void Rearrange(string s, int n)
{
    // Initially assume that we can kept
    // any symbol at any positions.
    // If at any index contains one then it is not
    // counted in our required positions
    fill(sieve + 1, sieve + n + 1, 1);
 
    // To store number of positions required
    // to store elements of same kind
    int sz = 0;
 
    // Start sieve
    for (int i = 2; i <= n / 2; i++) {
        if (sieve[i]) {
            // For all multiples of i
            for (int j = 1; i * j <= n; j++) {
                if (sieve[i * j])
                    sz++;
                sieve[i * j] = 0;
            }
        }
    }
 
    // map to store frequency of each character
    map<char, int> m;
    for (auto it : s)
        m[it]++;
 
    // Store all characters in the vector and
    // sort the vector to find the character with
    // highest frequency
    vector<pair<int, char> > v;
    for (auto it : m)
        v.push_back({ it.second, it.first });
    sort(v.begin(), v.end());
 
    // If most occurred character is less than
    // required positions
    if (v.back().first < sz) {
        cout << -1;
        return;
    }
 
    // In all required positions keep
    // character which occurred most times
    for (int i = 2; i <= n; i++) {
        if (!sieve[i]) {
 
            ans[i] = v.back().second;
        }
    }
 
    // Fill all other indexes with
    // remaining characters
    int idx = 0;
    for (int i = 1; i <= n; i++) {
        if (sieve[i]) {
            ans[i] = v[idx].second;
            v[idx].first--;
            // If character frequency becomes
            // zero then go to next character
            if (v[idx].first == 0)
                idx++;
        }
        cout << ans[i];
    }
}
 
// Driver code
int main()
{
    string str = "aabaaaa";
 
    int n = str.size();
 
    // Function call
    Rearrange(str, n);
 
    return 0;
}

Python3

# Python3 program to rearrange the given
# string such that all prime multiple
# indexes have same character
 
N = 100005
 
# To store answer
ans = [0]*N;
# sieve = [1]*N;
 
# Function to rearrange the given string
# such that all prime multiple indexes
# have the same character.
def Rearrange(s, n) :
 
    # Initially assume that we can kept
    # any symbol at any positions.
    # If at any index contains one then it is not
    # counted in our required positions
    sieve = [1]*(N+1);
     
    # To store number of positions required
    # to store elements of same kind
    sz = 0;
     
    # Start sieve
    for i in range(2, n//2 + 1) :
        if (sieve[i]) :
             
            # For all multiples of i
            for j in range(1, n//i + 1) :
                if (sieve[i * j]) :
                    sz += 1;
                sieve[i * j] = 0;
                 
    # map to store frequency of each character
    m = dict.fromkeys(s,0);
     
    for it in s :
        m[it] += 1;
         
    # Store all characters in the vector and
    # sort the vector to find the character with
    # highest frequency
    v = [];
    for key,value in m.items() :
        v.append([ value, key] );
     
    v.sort();
     
    # If most occurred character is less than
    # required positions
    if (v[-1][0] < sz) :
        print(-1,end="");
        return;
         
    # In all required positions keep
    # character which occurred most times
    for i in range(2, n + 1) :
        if (not sieve[i]) :
            ans[i] = v[-1][1];
             
    # Fill all other indexes with
    # remaining characters
    idx = 0;
     
    for i in range(1, n + 1) :
        if (sieve[i]):
            ans[i] = v[idx][1];
            v[idx][0] -= 1;
             
            # If character frequency becomes
            # zero then go to next character
            if (v[idx][0] == 0) :
                idx += 1;
                 
        print(ans[i],end= "");
         
         
# Driver code
if __name__ == "__main__" :
 
    string = "aabaaaa";
 
    n = len(string);
 
    # Function call
    Rearrange(string, n);
 
# This code is contributed by AnkitRai01
Producción:

baaaaaa

Publicación traducida automáticamente

Artículo escrito por pawan_asipu y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *