본문 바로가기

Algorithm_BOJ(백준)/그리디(Greedy Algorithm)

[백준 2217 c++] 로프

728x90
반응형

문제 링크

www.acmicpc.net/problem/2217

 

2217번: 로프

N(1 ≤ N ≤ 100,000)개의 로프가 있다. 이 로프를 이용하여 이런 저런 물체를 들어올릴 수 있다. 각각의 로프는 그 굵기나 길이가 다르기 때문에 들 수 있는 물체의 중량이 서로 다를 수도 있다. 하

www.acmicpc.net

문제 접근

// 접근: 여러 줄들의 최대중량 -> 그리디

// 최대중량은 = 선탣된 로프중 최소중량의 로프 * 로프의 개수

 





 

문제 풀이

// 풀이: 벡터에 저장 후 오름차순으로 정렬 후 최대중량이 제일 큰 값을 출력

 

 

 

 

 

주의

 

 

개념

// 개념: 내림차순 정렬 sort(v.begin(), v.end(),greater<int>());

 

소스코드

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio> // c 문법 헤더파일
#include<string> // c++ 문자열 클래스
#include<vector> // 동적배열 라이브러리
#include<stack>
#include<queue>
#include<algorithm>  // sort와 unique 사용
#include<cmath> // 제곱이나 루트함수 사용
#include<cstring> // memset 함수
#include <set>
#include <map> // map구조체

// [백준 2217 c++] 로프
// 접근: 여러 줄들의 최대중량 -> 그리디
// 최대중량은 = 선탣된 로프중 최소중량의 로프 * 로프의 개수
// 풀이: 벡터에 저장 후 오름차순으로 정렬 후 최대중량이 제일 큰 값을 출력
// 개념: 내림차순 정렬 sort(v.begin(), v.end(),greater<int>());

using namespace std; // cin,cout 편하게 사용 라이브러리

int n;
vector<int> v;
int max_weight = 0;
int Max = 0;
int main()
{
	// IO 속도 향상
	//ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int tp;
		cin >> tp;
		v.push_back(tp);
	}

	sort(v.begin(), v.end(),greater<int>());
	Max = v[0];
	for (int i = 0; i <n; i++)
	{
		max_weight = v[i] * (i+1);
		if (max_weight > Max)
		{
			Max = max_weight;
		}
    }
	cout << Max << '\n';

	 return 0;
}

반응형