MewwSikk
article thumbnail

๋ฌธ์ œ ์œ ํ˜•

๋ธŒ๋ฃจํŠธํฌ์Šค, permutation

 

์‚ฌ์šฉ ์–ธ์–ด

ํŒŒ์ด์ฌ, C++

 

 

ํ•ด๊ฒฐ์˜ ๊ธฐ๋ณธ ์•„์ด๋””์–ด

Permutation(์ˆœ์—ด)์„ ๊ธฐ๋ณธ ์•„์ด๋””์–ด๋กœ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

ํŒŒ์ด์ฌ์—์„œ๋Š” itertools๋ผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— permutationํ•จ์ˆ˜๊ฐ€ ์žˆ์–ด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•˜์˜€์ง€๋งŒ, CPP์—๋Š” ์—†์—ˆ๊ธฐ์— ํด๋ž˜์Šค ๋‚ด๋ถ€์— dfs๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Permutation์„ ๊ตฌํ˜„ํ•˜์˜€๋‹ค.

์ฝ”๋“œ

<CPP>

#include <iostream>
#include <vector>

using namespace std;

int cal(int op, int a, int b) {
    if (op == 0)
        return a + b;
    else if (op == 1)
        return a - b;
    else if (op == 2)
        return a * b;
    else
        return a / b;
}

class Perm {
    vector<int> perm;
    vector<int> nums;
    vector<int> tot;
    int n;
public:
    Perm() {
        cin >> n;
        for (int i = 0; i < n; i++) {
            int tmp;
            cin >> tmp;
            nums.push_back(tmp);
        }
        for (int i = 0; i < 4; i++) {
            int tmp;
            cin >> tmp;
            for (int j = 0; j < tmp; j++)
                perm.push_back(i);
        }
    }

    void swap(int& a, int& b) {
        int tmp = a;
        a = b;
        b = tmp;
    }

    void perms(int fix) {
        for (int i = fix; i < perm.size(); i++) {
            swap(perm[i], perm[fix]);
            perms(fix+1);
            swap(perm[i], perm[fix]);
        }
        if (fix == perm.size()) {
            int res = nums[0];
            for (int i = 0; i < perm.size(); i++)
                res = cal(perm[i], res, nums[i+1]);
            tot.push_back(res);
        }
    }
    void max_min() {
        int max = tot[0];
        int min = tot[0];
        for (int i = 1; i < tot.size(); i++) {
            if (max < tot[i])
                max = tot[i];
            if (min > tot[i])
                min = tot[i];
        }
        std::cout << int(max) << std::endl;
        std::cout << int(min) << std::endl;
    }
    void result() {
        perms(0);
        max_min();
    }
};

int main() {
    Perm p;
    p.result();
    return 0;
}

<Python>

import itertools

def cal(op, a, b):
	if op == 0:
		return a + b
	elif op == 1:
		return a - b
	elif op == 2:
		return a * b
	else:
		return a // b if a > 0 else -(-a // b)


n=int(input())
nums = list(map(int, input().split()))
ops=[]
for idx, i in enumerate(map(int, input().split())):
	ops.extend([idx]*i)
# visit=[False for _ in range(len(ops))]
tot=set()


for perm in set(itertools.permutations(ops, len(ops))):
	res = nums[0]
	for idx, p in enumerate(perm):
		res=cal(p,res,nums[idx+1])
	tot.add(res)
print(max(tot))
print(min(tot))

 

'๐Ÿ“š Algorithm' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

๋ฐฑ์ค€ 17142 - ์—ฐ๊ตฌ์†Œ 3 (python)  (0) 2024.07.13
๋ฐฑ์ค€ 2606 - ๋ฐ”์ด๋Ÿฌ์Šค (python)  (0) 2024.07.13
profile

MewwSikk

@Mu Gyum

ํฌ์ŠคํŒ…์ด ์ข‹์•˜๋‹ค๋ฉด "์ข‹์•„์š”โค๏ธ" ๋˜๋Š” "๊ตฌ๋…๐Ÿ‘๐Ÿป" ํ•ด์ฃผ์„ธ์š”!