Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 시뮬레이션
- 그래프
- VR
- 유니온 파인드
- 수학
- 알고리즘
- DFS
- 유니티
- ue5
- Team Fortress 2
- XR Interaction Toolkit
- 자료구조
- 브루트포스
- 스택
- 다이나믹 프로그래밍
- c++
- 우선순위 큐
- 백준
- BFS
- 구현
- 문자열
- 다익스트라
- 백트래킹
- 트리
- 투 포인터
- 누적 합
- 그리디 알고리즘
- Unreal Engine 5
- 정렬
- 재귀
Archives
- Today
- Total
1일1알
백준 1342번 행운의 문자열 C++ 본문
백트래킹을 이용하여 위치를 재배치한 모든 문자열을 구할 수 있다.
첫 번째 예제는 abababa 라는 문자열 하나만 행운의 문자열이지만, 답을 구해보면 144가 나오는데, 그 이유는 abababa 라는 문자가 144번 중복되어서 나오기 때문이다.
이를 해결하기 위해 a의 개수 4, b의 개수 3을 팩토리얼 연산을 하고 곱해준 뒤 답에서 나눠주어야 한다.
4! = 24, 3! = 6이고 24*6 = 144이다. 처음에 구한 답이 144이고 이것을 144로 나누면 1이 나온다.
알파벳의 각각의 개수의 정보를 저장하는 데 unordered_map 자료구조를 사용하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
string str;
bool visited[10] = { false };
int cnt = 0;
unordered_map<char, int> um;
int fac(int n) {
if (n == 0) return 1;
if (n == 1) return 1;
return n * fac(n - 1);
}
void BT(string s) {
if (s.length() == str.length()) {
cnt++;
return;
}
for (int i = 0; i < str.length(); i++) {
if (visited[i]) continue;
if (s.length() == 0) {
visited[i] = true;
BT(s + str[i]);
visited[i] = false;
}
else {
if (s[s.length() - 1] == str[i]) continue;
visited[i] = true;
BT(s + str[i]);
visited[i] = false;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int div = 1;
cin >> str;
for (int i = 0; i < str.length(); i++) {
um[str[i]]++;
}
for (auto a : um) {
div *= fac(a.second);
}
BT("");
cout << cnt / div;
};
'알고리즘' 카테고리의 다른 글
백준 2002번 추월 C++ (0) | 2021.12.05 |
---|---|
백준 11568번 민균이의 계략 C++ (0) | 2021.12.04 |
백준 2410번 2의 멱수의 합 C++ (0) | 2021.12.02 |
백준 15900번 나무 탈출 C++ (0) | 2021.12.01 |
백준 4889번 안정적인 문자열 C++ (0) | 2021.11.30 |