Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[그리디] 9월 27일 #5

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 02_스택_큐_덱/10757.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#include <iostre>
45 changes: 45 additions & 0 deletions 05_우선순위큐/14235.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <iostream>
#include <queue>

using namespace std;

int main()
{

ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);

int n,a;
priority_queue<int, vector<int>, less<int>> pq;
//큰 것 부터 나오는 less<int>

cin >> n;

while(n--) {
cin >> a;

//아이들 만남
if(a==0) {

if (pq.empty()) { //줄 선물 없으면 -1 출력
cout << "-1\n";
} else{ //가장 가치 큰 선물이 맨 위로 정렬되어 있으니, top, pop!
cout << pq.top() << "\n";
pq.pop();
}

}

//선물 충전
else {
for(int i=0; i<a; i++) {
int gift=0;
cin >> gift;
pq.push(gift);
}
}

}

return 0;
}
49 changes: 49 additions & 0 deletions 05_우선순위큐/2075.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <iostream>
#include <queue> //큐 헤더파일

using namespace std;

/*
HINT : 상위 n개의 숫자에서 n번째 숫자는 가장 작은 숫자네요!
*/

/*
입력되는 수 중 n번째로 큰 수를 찾자!
-> 최종으로 상위 n개를 저장할 수 있는 구조 -> n개 이상일 때 가장 작은 값을 삭제할 수 있는 구조
-> 최소힙을 이용하자
-> 입력을 최소힙에 push하고 힙의 사이즈가 n보다 크다면 top값을 제거해주자
->최종적으로 상위 n개의 숫자가 저장되고 top값이 n번째 큰 수가 된다!
*/


int main() {

//속도 향상 코드
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);


int n, num; //n과 각 숫자를 담을 변수
priority_queue<int, vector<int>, greater<int>> pq; //최소힙.
//greater : 오름차순 정렬 / 가장 작은 수가 스택 탑에!

//입력
cin >> n;

//연산
for (int i = 0; i < n * n; i++) {
cin >> num; //n^2개 숫자 입력받기
pq.push(num); //스택에 입력받은 수 넣기

//pq의 size를 n개 이하로 유지하여 메모리 초과 방지
if (pq.size() > n) {
pq.pop(); //pq에서 가장 작은 값 제거
}
}

//출력
//pq에 n * n개의 수 중 가장 큰 n개가 남았으므로 그 중 가장 작은 값(top)이 n번째로 큰 수
cout << pq.top();

return 0;
}
113 changes: 113 additions & 0 deletions 05_우선순위큐/2607.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
#include <iostream>

using namespace std;

bool similarWord(string word, string str) {


//두 단어의 알파벳 갯수 저장
int alpW[26]={0};
int alpS[26]={0};

//두 단어의 알파벳 갯수 카운트
for(int i=0; i<word.length(); i++) {
//만약 word의 i번째 문자가 A면 alpW의 0번 인덱스가 +1
alpW[(int)word[i]-65]++; //'A'=65
}

for(int i=0; i<str.length(); i++) {
//만약 str의 i번째 문자가 B면 alpS의 1번 인덱스가 +1
alpS[(int)str[i]-65]++; //'A'=65
}




int sameAlp=0;
for(int i=0; i<26; i++) {
if(alpS[i]==alpW[i]) {
sameAlp++;
}
}

//아예 구성 같은 경우
if(sameAlp==26) {
return true;
}


//하나 바꿔서 같아지는 경우
else if(sameAlp==24) {
int swap[2]; //서로 바꿀 두 변수
int j=0;

for(int i=0; i<26; i++) {
if(alpS[i]!=alpW[i]) {
swap[j++]=i;
if(j==2) {
break;
}
}
}

if((alpW[swap[0]]-alpS[swap[0]]) ==1 && (alpW[swap[1]]-alpS[swap[1]]) ==-1) {
return true; //스와핑 가능
} else if((alpW[swap[0]]-alpS[swap[0]]) ==-1 && (alpW[swap[1]]-alpS[swap[1]]) ==1) {
return true; //스와핑 가능
}
}


//하나 더하거나 빼서 같아지는 경우
else if(sameAlp==25) {

int difAlp=0;

for(int i=0; i<26; i++) {
if(alpS[i]!=alpW[i]) {
difAlp=i;
break;
}
}

if(abs(alpW[difAlp]-alpS[difAlp])==1) {
return true;
//25개가 같은데 하나만 갯수가 1 차이나면 더하거나 빼면 돼.
}
}




return false; //위에서 안걸리면 비슷해질 수 없어
}

int main()
{

ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);

int n;
string word; //기준 단어
int cnt=0; //비슷한 단어 개수

cin >> n >> word;

while(n>1) {

string str;
cin >> str;

if(similarWord(word, str)) {
cnt++;
}

n--;
}

cout<<cnt;

return 0;
}
56 changes: 56 additions & 0 deletions 06_그리디/1213.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // reverse 함수를 사용하기 위한 헤더

using namespace std;

int main() {

ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);

string line;
cin >> line;

vector<int> alpha(26, 0);
for (int i = 0; i < line.length(); i++) {
int idx = line[i] - 'A';
alpha[idx]++;
}

int isOne = 0; //홀수개 알파벳 개수 담을 변수
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3
알튜비튜에서는 변수명에는 스네이크 표기법을 사용하고 있어요! is_one과 같은 이름은 어떨까요?

for (int i = 0; i < alpha.size(); i++) {
if (alpha[i] % 2 != 0) isOne++;
}

string answer = "";
string sb = "";
if (isOne > 1) {
answer += "I'm Sorry Hansoo";
}
Comment on lines +29 to +31
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

팰린드롬을 만들 수 없는 조건을 잘 발견해주셨네요!👍


else
//펠린드롬 만들기
{
for (int i = 0; i < alpha.size(); i++) {
for (int r = 0; r < alpha[i] / 2; r++) {
sb += (char)(i + 'A');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3
char 없이도 문자형으로 잘 들어갑니다!

}
}
answer += sb;
string end = sb;
reverse(end.begin(), end.end());

sb = "";
for (int i = 0; i < alpha.size(); i++) {
if (alpha[i] % 2 == 1) {
sb += (char)(i + 'A');
}
}
answer += sb + end;
}
cout << answer << "\n";

return 0;
}
37 changes: 37 additions & 0 deletions 06_그리디/17451.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <iostream>
#include <vector>

using namespace std;

int main() {

ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);

//입력받기
int n = 0;
cin >> n;

vector<long long> planet(n);
for (int i = 0; i < n; i++) {
cin >> planet[i];
}

//행성 이동 때 필요한 속도!
long long velocity = planet[n - 1];

//뒤의 행성부터 연산!
for (int i = n - 2; i >= 0; i--) {
if (velocity < planet[i]) { //필요한 속도보다 작은 경우
velocity = planet[i];
}
//배수 아니면, 양의 배수로 만들면서 앞으로 진행!
else if (planet[i] < velocity && velocity % planet[i] != 0) {
velocity = ((velocity / planet[i]) + 1) * planet[i];
}
}
Comment on lines +24 to +32
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

최소 속도를 만드는 조건을 파악해서 문제를 잘 풀어주셨네요!👍


cout << velocity << "\n";

return 0;
}
82 changes: 82 additions & 0 deletions 06_그리디/18111.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#include <iostream>
#include <vector>

using namespace std;

typedef pair<int, int> pii; // 두 정수 저장하기 위해 typedef 선언

const int MAX_HEIGHT = 257; //최대 높이 상수로 저장
const int INF = 987'654'321; //가능한 최댓값이 12,800,000이므로 많이 쓰는 큰 수인 987654321을 사용했습니다! INF관련 글을 한번 읽어보세요!

// 모든 땅의 높이를 height로 만드는 비용 계산
int calcCost(int height, int n, int m, int b, vector<vector<int>>& blocks) {
int cost = 0; // 총 비용
int added = 0; // 추가해야 하는 블록의 총 개수
int removed = 0; // 제거해야 하는 블록의 총 개수

// 모든 블록에 대해 이중 반복
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int gap = abs(height - blocks[i][j]); // 목표 높이와 현재 블록의 높이 차이 계산

if (blocks[i][j] > height) {// 목표 높이보다 높은 칸인 경우,
removed += gap; //gap개의 블록 제거
}
else if (blocks[i][j] < height) {// 목표 높이보다 낮은 칸인 경우,
added += gap; //gap개의 블록 추가
}
}
}

// 전체 비용 계산
cost = 2 * removed + added;

// 블록 개수가 부족하다면 모든 땅의 높이를 height로 만드는 것이 불가능
return (added > (b + removed)) ? INF : cost;
}

// 모든 땅의 높이를 같게 만드는 최소 비용과 그 때의 땅의 높이
pii makeGroundEven(int n, int m, int b, vector<vector<int>>& ground) {
int minCost = INF; //최소 비용 초기화
int height = 0; //최적 높이 초기화

// 모든 가능한 높이에 대해 반복하며 최소 비용 찾기
for (int i = 0; i < MAX_HEIGHT; i++) {
int cost = calcCost(i, n, m, b, ground); // 현재 높이로 모든 땅의 높이를 맞출 때의 비용 계산
if (cost <= minCost) { //최소 비용이 갱신됐다면,
minCost = cost; //최소 비용 업데이트
height = i; //현재 높이 저장
}
}

return {minCost, height};
}

/**
* 블록 높이의 최댓값이 256밖에 되지 않으므로
* 모든 칸을 높이 n(0~256)으로 만드는 모든 경우를 시도해보고
* 그 중에서 비용이 최소가 될 때를 찾는다.
*
* 모든 칸을 높이 n으로 만드는
*/

int main() {
int n, m, b;

// 입력 받기
cin >> n >> m >> b;
vector<vector<int>> ground(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> ground[i][j];
}
}

// 연산 수행
pii answer = makeGroundEven(n, m, b, ground);

// 출력
cout << answer.first << " " << answer.second << "\n";

return 0;
}