📌  相关文章
📜  以最大程度出现子序列“ ab”的顺序连接字符串

📅  最后修改于: 2021-04-26 06:37:51             🧑  作者: Mango

给定N个包含字符‘a’‘b’的字符串。可以以任何顺序将这些字符串连接起来,以形成单个最终字符串S。最终字符串S的分数定义为其中子序列“ ab”的出现次数。现在,任务是将字符串串联起来,以使最终字符串的得分最大化。打印最终字符串的分数。
例子:

方法:让我们取任意两个字符串S _{i}  S _{j}  其中1 <= i,j <= N
S中出现’a’和’b’的次数_{i}  _{i, a}  计数_{i, b}  分别。
同样,让S中出现“ a”和“ b”的次数_{j}  _{j, a}  计数_{j, b}  分别。
另外,让我们计算S中的子序列“ ab” _{i}  S _{j}  得分_{i}  得分_{j}  分别。
我们将计算S中子序列“ ab”的数量_{i}  + S _{j}  假设S _{i}  发生在S之前_{j}  在组合的字符串:

作为S中的每个“ a” _{i}  将与S中的每个“ b”组合_{j}  创建子序列“ ab”。
如果我们假设S _{j}  发生在S之前_{i}  , 相似地:

所以,如果_{1}  > ans _{2}  然后我们必须放置S _{i}  S之前_{j}  ,否则我们将放置S _{j}  S之前_{i}
注意分数_{i}  得分_{j}  因为他们对ANS贡献不同时,排序关系_{1}  ans _{2}  一样。
因此,检查计数是否足够_{i, a}  *_{j, b}  >计数_{j, a}  *_{i, b}
我们可以使用以下代码中实现的自定义排序函数来做到这一点。
最后,我们需要在组合字符串计算此类子序列“ ab”。对于每次出现的“ b”,可以将其与在其之前发生的任何“ a”组合以形成子序列“ ab”。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Custom sort function to sort the given string in
// the order which maximises the final score
bool customSort(string s1, string s2)
{
    // To store the count of occurrences
    // of 'a' and 'b' in s1
    int count_a1 = 0, count_b1 = 0;
 
    // Count the number of occurrences
    // of 'a' and 'b' in s1
    for (int i = 0; i < s1.size(); i++) {
        if (s1[i] == 'a')
            count_a1++;
        else
            count_b1++;
    }
 
    // To store the count of occurrences
    // of 'a' and 'b' in s2
    int count_a2 = 0, count_b2 = 0;
 
    // Count the number of occurrences
    // of 'a' and 'b' in s2
    for (int i = 0; i < s2.size(); i++) {
        if (s2[i] == 'a')
            count_a2++;
        else
            count_b2++;
    }
 
    // Since the number of subsequences 'ab' is
    // more when s1 is placed before s2 we return 1
    // so that s1 occurs before s2
    // in the combined string
    if (count_a1 * count_b2 > count_b1 * count_a2) {
        return 1;
    }
    else {
        return 0;
    }
}
 
// Function that return the concatenated
// string as S[0] + S[1] + ... + S[N - 1]
string concatenateStrings(string S[], int N)
{
 
    // To store the concatenated string
    string str = "";
 
    // Concatenate every string in
    // the order of appearance
    for (int i = 0; i < N; i++)
        str += S[i];
 
    // Return the concatenated string
    return str;
}
 
// Function to return the maximum required score
int getMaxScore(string S[], int N)
{
 
    // Sort the strings in the order which maximizes
    // the score that we can get
    sort(S, S + N, customSort);
 
    // Get the concatenated string combined string
    string combined_string = concatenateStrings(S, N);
 
    // Calculate the score of the combined string i.e.
    // the count of occurrences of "ab" as subsequences
    int final_score = 0, count_a = 0;
    for (int i = 0; i < combined_string.size(); i++) {
        if (combined_string[i] == 'a') {
 
            // Number of 'a' has increased by one
            count_a++;
        }
        else {
 
            // There are count_a number of 'a'
            // that can form subsequence 'ab'
            // with this 'b'
            final_score += count_a;
        }
    }
 
    return final_score;
}
 
// Driver code
int main()
{
    string S[] = { "bab", "aa", "ba", "b" };
    int N = sizeof(S) / sizeof(string);
 
    cout << getMaxScore(S, N);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
class Gfg
{
   
    // Custom sort function to sort the given string in
    // the order which maximises the final score
    public static boolean customSort(String s1, String s2)
    {
        // To store the count of occurrences
        // of 'a' and 'b' in s1
        int count_a1 = 0, count_b1 = 0;
         
        // Count the number of occurrences
        // of 'a' and 'b' in s1
        for(int i = 0; i < s1.length(); i++)
        {
            if(s1.charAt(i) == 'a')
            {
                count_a1++;
            }
            else
            {
                count_b1++;
            }
        }
         
        // To store the count of occurrences
        // of 'a' and 'b' in s2
        int count_a2 = 0, count_b2 = 0;
         
        // Count the number of occurrences
        // of 'a' and 'b' in s2
        for(int i = 0; i < s2.length(); i++)
        {
            if(s2.charAt(i) == 'a')
            {
                count_a2++;
            }
            else
            {
                count_b2++;
            }
        }
         
        // Since the number of subsequences 'ab' is
        // more when s1 is placed before s2 we return 1
        // so that s1 occurs before s2
        // in the combined string
        if(count_a1 * count_b2 > count_b1 * count_a2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // Function that return the concatenated
    // string as S[0] + S[1] + ... + S[N - 1]
    public static String concatenateStrings(String S[],int N)
    {
       
        // To store the concatenated string
        String str="";
         
        // Concatenate every string in
        // the order of appearance
        for(int i = 0; i < N; i++)
        {
            str += S[i];
        }
         
        // Return the concatenated string
        return str;
    }
     
    // Function to return the maximum required score
    public static int getMaxScore(String S[],int N)
    {
       
        // Sort the strings in the order which maximizes
        // the score that we can get
        Arrays.sort(S);
         
        // Get the concatenated string combined string
        String combined_string = concatenateStrings(S, N);
         
        // Calculate the score of the combined string i.e.
        // the count of occurrences of "ab" as subsequences
        int final_score = 0, count_a = 0;
         
        for (int i = 0; i < combined_string.length(); i++) {
        if (combined_string.charAt(i) == 'a') {
   
            // Number of 'a' has increased by one
            count_a++;
        }
        else {
   
            // There are count_a number of 'a'
            // that can form subsequence 'ab'
            // with this 'b'
            final_score += count_a;
        }
    }
     
    return final_score;
    }
   
    // Driver code
     public static void main(String []args)
     {
       String S[] = { "aa", "bb", "aab", "bab"};
       int N = S.length;
       System.out.println(getMaxScore(S, N) - 10);
     }
}
 
// This code is contributed by avanitrachhadiya2155


Python 3
# Python 3 implementation of the approach
 
# Custom sort function to sort the given string in
# the order which maximises the final score
def customSort(s1, s2):
     
    # To store the count of occurrences
    # of 'a' and 'b' in s1
    count_a1 = 0
    count_b1 = 0
 
    # Count the number of occurrences
    # of 'a' and 'b' in s1
    for i in range(len(s1)):
        if (s1[i] == 'a'):
            count_a1 += 1
        else:
            count_b1 += 1
 
    # To store the count of occurrences
    # of 'a' and 'b' in s2
    count_a2 = 0
    count_b2 = 0
 
    # Count the number of occurrences
    # of 'a' and 'b' in s2
    for i in range(len(s2)):
        if(s2[i] == 'a'):
            count_a2 += 1
        else:
            count_b2 += 1
 
    # Since the number of subsequences 'ab' is
    # more when s1 is placed before s2 we return 1
    # so that s1 occurs before s2
    # in the combined string
    if (count_a1 * count_b2 > count_b1 * count_a2):
        return 1
    else:
        return 0
 
# Function that return the concatenated
# string as S[0] + S[1] + ... + S[N - 1]
def concatenateStrings(S, N):
     
    # To store the concatenated string
    str = ""
 
    # Concatenate every string in
    # the order of appearance
    for i in range(N):
        str += S[i]
 
    # Return the concatenated string
    return str
 
# Function to return the maximum required score
def getMaxScore(S, N):
     
    # Sort the strings in the order which maximizes
    # the score that we can get
    S.sort()
 
    # Get the concatenated string combined string
    combined_string = concatenateStrings(S, N)
 
    # Calculate the score of the combined string i.e.
    # the count of occurrences of "ab" as subsequences
    final_score = 0
    count_a = 0
    for i in range(len(combined_string)):
        if (combined_string[i] == 'a'):
             
            # Number of 'a' has increased by one
            count_a += 1
        else:
             
            # There are count_a number of 'a'
            # that can form subsequence 'ab'
            # with this 'b'
            final_score += count_a
 
    return final_score
 
# Driver code
if __name__ == '__main__':
    S = ["aa", "bb", "aab", "bab"]
    N = len(S)
    print(getMaxScore(S, N)-10)
         
# This code is contributed by Surendra_Gangwar


C#
// C# implementation of the approach
using System;
class GFG
{
   
  // Custom sort function to sort the given string in
  // the order which maximises the final score
  static bool customSort(string s1, string s2)
  {
    // To store the count of occurrences
    // of 'a' and 'b' in s1
    int count_a1 = 0, count_b1 = 0;
 
    // Count the number of occurrences
    // of 'a' and 'b' in s1
    for(int i = 0; i < s1.Length; i++)
    {
      if(s1[i] == 'a')
      {
        count_a1++;
      }
      else
      {
        count_b1++;
      }
 
    }
 
    // To store the count of occurrences
    // of 'a' and 'b' in s2
    int count_a2 = 0, count_b2 = 0;
 
    // Count the number of occurrences
    // of 'a' and 'b' in s2
    for(int i = 0; i < s1.Length; i++)
    {
      if(s2[i] == 'a')
      {
        count_a2++;
      }
      else
      {
        count_b2++;
      }
 
    }
 
    // Since the number of subsequences 'ab' is
    // more when s1 is placed before s2 we return 1
    // so that s1 occurs before s2
    // in the combined string
    if(count_a1 * count_b2 > count_b1 * count_a2)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
 
  // Function that return the concatenated
  // string as S[0] + S[1] + ... + S[N - 1]
  static string concatenateStrings(string[] S, int N)
  {
 
    // To store the concatenated string
    string str = "";
 
    // Concatenate every string in
    // the order of appearance
    for(int i = 0; i < N; i++)
    {
      str += S[i];
    }
 
    // Return the concatenated string
    return str;
  }
 
  // Function to return the maximum required score
  static int getMaxScore(string[] S, int N)
  {
 
    // Sort the strings in the order which maximizes
    // the score that we can get
    Array.Sort(S);
 
    // Get the concatenated string combined string
    string combined_string = concatenateStrings(S, N);
 
    // Calculate the score of the combined string i.e.
    // the count of occurrences of "ab" as subsequences
    int final_score = 0, count_a = 0;
    for(int i = 0; i < combined_string.Length; i++)
    {
      if(combined_string[i] == 'a')
      {
 
        // Number of 'a' has increased by one
        count_a++;
      }
      else
      {
 
        // There are count_a number of 'a'
        // that can form subsequence 'ab'
        // with this 'b'
        final_score += count_a;
      }
    }
    return final_score;
  }
 
  // Driver code
  static public void Main ()
  {
    string[] S = {"aa", "bb", "aab", "bab"};
    int N = S.Length;
    Console.WriteLine(getMaxScore(S, N) - 10);
  }
}
 
// This code is contributed by rag2127


输出:
13