중요: 그리디 알고리즘은 모든 문제에 적합하지는 않음
알고리즘:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n; // 거스름돈
cin >> n;
vector<int> coins = {500, 100, 50, 10, 5, 1};
int count = 0;
for (int coin : coins)
{
count += n / coin; // 현재 동전으로 줄 수 있는 최대 개수(큰 동전부터 시작)
n %= coin; // 나머지 금액 계산
}
cout << count << endl;
return 0;
}
알고리즘:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<int, int>> meetings;
for (int i = 0; i < n; i++)
{
int start, end;
cin >> start >> end;
if (start >= end)
{
cout << "종료시간이 시작시간보다 빠름" << endl;
return 0;
}
meetings.push_back({ end, start }); // 종료 시간 기준 (종료, 시작) 순으로 저장
}
sort(meetings.begin(), meetings.end()); // 종료 시간이 빠른 순으로 정렬
int count = 0, last_end_time = 0;
for (auto meeting : meetings)
{
if (meeting.second >= last_end_time)
{ // 시작 시간이 마지막 종료 시간 이후라면
last_end_time = meeting.first; // 종료 시간 업데이트
count++;
}
}
cout << count << endl;
return 0;
}
알고리즘:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item
{
int weight;
int value;
};
bool compare(Item a, Item b)
{
return (double)a.value / a.weight > (double)b.value / b.weight;
}
int main() {
int n, W; // 아이템 수, 배낭 용량
cin >> n >> W;
vector<Item> items(n);
for (int i = 0; i < n; i++)
{
cin >> items[i].weight >> items[i].value;//아이템struct 의 weight, value 저장
}
sort(items.begin(), items.end(), compare); // 무게 기준으로 정렬
double max_value = 0;
for (int i = 0; i < n; i++)
{
if (W >= items[i].weight)
{ // 물건 전체를 담을 수 있으면
W -= items[i].weight;
max_value += items[i].value;
}
else
{ // 물건을 쪼개서 넣음
max_value += items[i].value * ((double)W / items[i].weight);
break;
}
}
cout << max_value << endl;
return 0;
}
postOrder, preOrder, inOrder (0) | 2025.01.21 |
---|---|
DFS(Depth First Search) (0) | 2025.01.20 |
그래프 vs 트리 (0) | 2025.01.13 |
벨만-포드 알고리즘 (Bellman-Ford Algorithm) (0) | 2025.01.13 |
재귀함수 Recursion (1) | 2025.01.06 |