๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 6443๋ฒˆ - ์• ๋„ˆ๊ทธ๋žจ

by ์•ˆ์ฃผํ˜• 2022. 8. 21.

๋ฌธ์ œ

 

6443๋ฒˆ: ์• ๋„ˆ๊ทธ๋žจ

์ฒซ์งธ ์ค„์— ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ N ์ด, ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์˜๋‹จ์–ด๊ฐ€ ๋“ค์–ด์˜จ๋‹ค. ์˜๋‹จ์–ด๋Š” ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 20๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๊ณ , ์• ๋„ˆ๊ทธ๋žจ์˜ ์ˆ˜๊ฐ€ 100,000๊ฐœ ์ดํ•˜์ธ ๋‹จ์–ด๋งŒ ์ž…๋ ฅ์œผ๋กœ ์ฃผ

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <algorithm>

using namespace std;

int main(){
    int N; cin>>N;
    while(N--){
        string inp; cin>>inp;
        
        sort(inp.begin(), inp.end());
        do{
            cout<<inp<<'\n';
        }while(next_permutation(inp.begin(), inp.end()));
    }
}

 

ํ’€์ด

ํ•ด๋‹น ์•ŒํŒŒ๋ฒณ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ๊ตฌํ•˜๋Š” ์ˆœ์—ด ๋ฌธ์ œ์˜€๋Š”๋ฐ next_permutation์„ ์‚ฌ์šฉํ•ด์„œ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ฒ˜์Œ์— ์•„๋ž˜์™€ ๊ฐ™์ด ์ง์ ‘ ์ˆœ์—ด์„ ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ ๊ณ„์† ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•ด์„œ ๋ฐฉ์•ˆ์„ ์ฐพ์ง€ ๋ชปํ•˜๊ณ  next_permutation์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

#include <iostream>
#include <vector>
#include <memory.h>
#include <algorithm>
#include <unordered_map>

using namespace std;
vector<string> ans;
bool visited[100001];
unordered_map<string,int> check;

void dfs(string make, string inp){
    if(inp.length() == make.length()){   // ๋ฐ”๋กœ๋ฐ”๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. ์ €์žฅํ•œ ํ›„์— ์ถœ๋ ฅํ•˜๋ฉด ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ ๋ฐœ์ƒ
        if(!check[make]){
            check[make]++;
            cout<<make<<'\n';
            return;
        }
    }
    for(int i=0; i<inp.length(); i++){
        if(visited[i]) continue;
        visited[i] = 1;
        dfs(make+inp[i], inp);
        visited[i] = 0;
    }
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    int N; cin>>N;
    
    for(int i=0; i<N; i++){
        string inp; cin>>inp;
        sort(inp.begin(), inp.end());   // ์ •๋ ฌ์„ ํ•œ ํ›„์— ๋ฐฑํŠธ๋ž™ํ‚น์„ ๋Œ๋ฆฌ์ž.
        dfs("", inp);
        memset(visited, 0 ,sizeof(visited));
    }
}

๋Œ“๊ธ€