431B - Shower Line - CodeForces Solution


brute force implementation *1200

Please click on ads to support us..

Python Code:

from itertools import permutations
from typing import List

def initial_order_for_maximum_happiness(mat: List[List[int]]) -> int:
    def calculate_happiness(student: List[int]) -> int:
        hap = 0
        n  = 5
        while student:
            pair = [(student[i], student[i+1]) for i in range(0, n-1, 2)]
            for i, j in pair:
                hap += mat[i][j]
                hap += mat[j][i]
            n -= 1
            student = student[1:]
        return hap
    num = [0, 1, 2, 3, 4]
    possible = list(permutations(num))
    happiness = 0
    for order in possible:
        hap = calculate_happiness(order)
        happiness = max(happiness, hap)
    return happiness

a = []
for i in range(5):
    b = [int(j) for j in input().split()]
    a.append(b)
d = initial_order_for_maximum_happiness(a)
print(d)

C++ Code:

#include <bits/stdc++.h>

using namespace std;
int g[6][6];
int main()
{
    int n=5;
    for(int i=0;i<n;i++)
        for(int j=0; j<n; j++)
            cin>>g[i][j];
    int p[6], pans[6], ans=-1, tmp;
    for(int i=0; i<n; ++i)
        p[i]=i;
    
    do{
        tmp=g[p[0]][p[1]]+g[p[1]][p[0]];
        tmp+=g[p[2]][p[3]]+g[p[3]][p[2]];
        
        tmp+=g[p[1]][p[2]]+g[p[2]][p[1]];
        tmp+=g[p[3]][p[4]]+g[p[4]][p[3]];
        
        tmp+=g[p[2]][p[3]]+g[p[3]][p[2]];
        
        tmp+=g[p[3]][p[4]]+g[p[4]][p[3]];
        
        if(tmp>ans){
            ans=tmp;
            for(int i=0; i<n; ++i)
                pans[i]=p[i];
        }
    }
    while(next_permutation(p, p+n));
    cout<<ans<<endl;

    return 0;
}


Comments

Submit
0 Comments
More Questions

881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV