/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 52ms 29.895 MiB
#2 Accepted 128ms 33.434 MiB
#3 Accepted 3342ms 35.98 MiB
#4 Time Exceeded ≥4098ms ≥45.293 MiB
#5 Time Exceeded ≥4104ms ≥190.605 MiB

Code

import itertools

M = 2 * 10**5 + 10
MOD = 1000000007

cost = [[0] * 26 for _ in range(26)]
all_permutations = []

def precal():
    vowel = "aeiou"
    
    # Fill the cost matrix for vowels
    for i in range(len(vowel)):
        l = i
        cnt = 0
        while cnt < 5:
            cost[ord(vowel[i]) - ord('a')][ord(vowel[l]) - ord('a')] = cnt
            l += 1
            cnt += 1
            if l == 5:
                l = 0
    
    all_permutations.append(vowel)
    
    # Generate all permutations of vowels and store them
    for perm in itertools.permutations(vowel):
        all_permutations.append(''.join(perm))

def main():
    precal()
    t = int(input())  # Number of test cases
    
    for _ in range(t):
        n = int(input())  # Length of the string
        s = input()  # The input string
        mx = MOD  # Initialize max value with a large number
        
        # Mapping each character to its position in the alphabet
        mp = {chr(ord('a') + i): i for i in range(26)}
        
        # Loop over all permutations of the vowels
        for perm in all_permutations:
            p = perm
            dp = [[0] * 5 for _ in range(n + 1)]  # dp[j][i] stores the minimum cost up to the j-th position and i-th vowel
            
            for i in range(5):
                for j in range(1, n + 1):
                    pro = cost[mp[s[j - 1]]][mp[p[i]]]  # Cost for the current character transition
                    if i == 0:
                        dp[j][i] = dp[j - 1][i] + pro
                    else:
                        dp[j][i] = dp[j - 1][i] + pro
                        dp[j][i] = min(dp[j][i], dp[j][i - 1])
            
            mx = min(mx, dp[n][i])
        
        print(mx)

if __name__ == "__main__":
    main()

Information

Submit By
Type
Submission
Problem
P1140 Vowel arrangement
Language
PyPy 3 (Python 3.9.18 PyPy 7.3.15)
Submit At
2024-11-27 16:18:39
Judged At
2024-11-27 21:09:41
Judged By
Score
41
Total Time
≥4104ms
Peak Memory
≥190.605 MiB