본문 바로가기

C++

(12)
[C++] 다익스트라 알고리즘 코드 구현 #include #include #include #define INF 1e9 #define MAX 10 using namespace std; int dist[7] vector graph[10]; vector Dijkstra(int start) { priority_queue pq; dist[start] = 0; pq.push({ -dist[start], start }); while (!pq.empty()) { int here = pq.top().second; int heredist = -pq.top().first; int size = graph[here].size(); pq.pop(); if (heredist > dist[here]) continue; for (int i = 0; i < size; i++)..
[C++] 부분 배낭 문제 (Fractional Knapsack Problem) / 그리디 알고리즘 #include #include #include #define _CRT_SECURE_NO_WARNINGS using namespace std; int main() { double data[5][2] = { {10, 10}, {15, 12}, {20, 10}, {25, 8}, {30, 5} }; double temp[2]; double total_value = 0.0; double capacity = 30.0; vector details; for(int i=0; i= elem[0]) { capacity -= elem[0]; total_value += elem[1]; details.push_back({elem[0], elem[1], 1}); } else { double fraction = capacity /..
[C++] BFS(너비우선탐색)알고리즘 코드 구현 #include #include #include #define _CRT_SECURE_NO_WARNINGS using namespace std; void bfs(vectorgraph[], int start_node) { vector visited; vector need_visit; need_visit.push_back(start_node); while (!need_visit.empty()) { int node = need_visit.front(); need_visit.erase(need_visit.begin()); if (find(visited.begin(), visited.end(), node) == visited.end()) { visited.push_back(node); for (int i = 0; ..
[C++] DFS(깊이 우선 탐색) 알고리즘 코드 구현 #include #include #include #define _CRT_SECURE_NO_WARNINGS using namespace std; void dfs(vectorgraph[], int start_node) { vector visited; vector need_visit; need_visit.push_back(start_node); while (!need_visit.empty()) { int node = need_visit.back(); need_visit.erase(need_visit.end() - 1); if (find(visited.begin(), visited.end(), node) == visited.end()) { visited.push_back(node); for (int i = 0;..
[C++] 이진탐색 구현 #include #include #include #include using namespace std; int binary_search(int arr[], int num, int start, int end) { int index = (start + end) / 2; if (start == end && arr[index] != num) return -100; if (arr[index] == num) return index; else if (arr[index] > num) binary_search(arr, num, start, index - 1); else binary_search(arr, num, index + 1, end); } void main() { int arr[17] = {1, 3, 5, 7, 11..
[C++] 재귀호출로 회문 판별하기 #include #include #include using namespace std; int palindrome(string arr,int start,int end) { if (start >= end) return 0; else if (arr[start] == arr[end]) return palindrome(arr, start + 1, end - 1); else return 1; } int main() { string arr; arr = "level"; int res; res = palindrome(arr, 0, arr.size() - 1); cout
[C++] 재귀호출로 배열의 합 구하기 #include #include using namespace std; int add(int arr[], int index) { if (index == 0) return arr[index]; else return arr[index] + add(arr, index - 1); } int main() { int arr[10], res; for (int i = 0; i < 10; i++) { arr[i] = rand() % 100; } res = add(arr, 9); cout
[C++] 재귀호출로 팩토리얼 구하기 #include #include using namespace std; int fact(int num) { if (num