๋ฌธ์
์ฝ๋
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#define MAX 9999999+1
using namespace std;
int visited[MAX];
vector<bool> prime (MAX, true); // true์ผ๋ ์์
int cnt = 0;
void permutation(string inp, string origin, int index){
if(inp.length()>origin.length()) return;
string number = inp;
reverse(number.begin(),number.end());
while(!number.empty()&&number.back()==0) number.pop_back(); // 0 ์ ๊ฑฐ
reverse(number.begin(),number.end());
if(!number.empty()&&prime[stoi(number)]&&!visited[stoi(number)]){ //์์๋ผ๋ฉด
visited[stoi(number)] = 1; //์ค๋ณต ๋ฐฉ์ง๋ฅผ ์ํ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
// cout<<"์กฐํฉ: "<< stoi(number)<<'\n';
cnt++;
}
for(int i=index; i<origin.length(); i++){
string temp = number + origin[i];
permutation(temp, origin, i+1);
}
}
int solution(string numbers) {
int answer = 0;
prime[0] = false, prime[1] = false;
for(int i=2; i<=MAX; i++){ //์์๋ฅผ ๊ตฌํ๋ ์๋ผํ ์คํ
๋ค์ค์ ์ฒด
if (prime[i] == true) {
int k = 2;
while (i * k <= MAX) {
prime[i * k] = false;
k++;
}
}
}
sort(numbers.begin(),numbers.end()); //์์ด ๋๋ฆฌ๊ธฐ ์ ์๋ ํ์๋ก ์ ๋ ฌํด์ผํจ
do{ //์์ด
permutation("",numbers, 0);
}while(next_permutation(numbers.begin(),numbers.end()));
answer = cnt;
return answer;
}
ํ์ด(31๋ถ)
๋จผ์ ์๋ผํ ์คํ ๋ค์ค์ ์ฒด ์๊ณ ๋ฆฌ์ฆ์ ํตํด์ ์์(prime number)๋ฅผ ๋ฏธ๋ฆฌ ์ ๋ถ ๊ตฌํด์ค๋๋ค. ๋ฌธ์์ด์ ์์ด๋ก ๋๋ ค์ ์กฐํฉํ์ ๋ ๊ทธ ์๊ฐ ์์์ธ์ง ์๋์ง๋ฅผ ๊ตฌ๋ถํ์ฌ ๊ตฌํํ์ต๋๋ค. ์์ ํ์ ๋ฌธ์ ์๋๋ฐ, ์ง๊ธ ์ฒ์์ next_permutation์ ์งํํ๊ธฐ ์ ์ ์ ๋ ฌ์ ํด์ค์ผ ํ๋ค๋ ์ฌ์ค์ ๊น๋นกํ๊ณ ์ ์ถํ๋ค๊ฐ 75์ ์ด ๋ ์ ์ด์ํ ๋ฐ์ ๊ณ ๋ฏผํ๋ค๊ฐ ์๊ฐ์ ์กฐ๊ธ ๋ง์ด ์๋นํ์ต๋๋ค.
๊ทธ๋ฆฌ๊ณ ์๋๋ ์ฌ๊ท ๋ง๊ณ for๋ฌธ์ ์ด์ฉํ ํ์ด์ ๋๋ค. ์๋๋ ์๋๊ฐ ์กฐ๊ธ ๋ ๋๋ ธ์ต๋๋ค.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#define MAX 9999999+1
using namespace std;
int visited[MAX];
vector<bool> prime (MAX, true); // true์ผ๋ ์์
int cnt = 0;
void permutation(string number){
string temp;
for(int i=0; i<number.length(); i++){
if(temp.empty()&&number[i]==0) continue;
temp+=number[i];
if(prime[stoi(temp)]&&!visited[stoi(temp)]){
visited[stoi(temp)] = 1;
cnt++;
}
}
}
int solution(string numbers) {
int answer = 0;
prime[0] = false; prime[1] = false;
for(int i=2; i<=MAX; i++){ //์์๋ฅผ ๊ตฌํ๋ ์๋ผํ ์คํ
๋ค์ค์ ์ฒด
if (prime[i] == true) {
int k = 2;
while (i * k <= MAX) {
prime[i * k] = false;
k++;
}
}
}
sort(numbers.begin(),numbers.end()); //์์ด ๋๋ฆฌ๊ธฐ ์ ์๋ ํ์๋ก ์ ๋ ฌํด์ผํจ
do{ //์์ด
permutation(numbers);
}while(next_permutation(numbers.begin(),numbers.end()));
answer = cnt;
return answer;
}
'Algorithm ๐ง๐ปโ๐ป > ํ๋ก๊ทธ๋๋จธ์ค(Programmers)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์นดํซ(Level 2) (0) | 2022.04.14 |
---|---|
[c++] ํ๋ก๊ทธ๋๋จธ์ค - 124 ๋๋ผ์ ์ซ์(Level 2) (0) | 2022.04.14 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ๋ฉ๋ด ๋ฆฌ๋ด์ผ(Level 2) (2) | 2022.04.13 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - [1์ฐจ] ๋น๋ฐ ์ง๋(Level 1) (0) | 2022.04.13 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - 3์ง๋ฒ ๋ค์ง๊ธฐ(Level 1) (0) | 2022.04.13 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์์ ๋ง๋ค๊ธฐ(Level 1) (0) | 2022.04.11 |
๋๊ธ