1일1알

백준 2296번 건물짓기 C++ 본문

알고리즘

백준 2296번 건물짓기 C++

영춘권의달인 2022. 2. 15. 11:38

https://www.acmicpc.net/problem/2296

 

1. 건물들을 x좌표 오름차순으로 정렬한다.

2. 좌표가 대각선 위로 올라가는 건물들과 대각선 아래로 내려가는 건물들의 이익을 따로 구하고 이익이 최대가 되는 경우를 구한다.

 

순열 문제와 비슷하게 푼 것 같다.

 

#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>
#include <iomanip>

using namespace std;
using ll = long long;

struct Building {
	int x;
	int y;
	int c;
};

bool compare(const Building& lhs, const Building& rhs) {
	return lhs.x < rhs.x;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n, x, y, c;
	cin >> n;
	vector<Building> v;
	vector<int> dp13(n, 0);
	vector<int> dp24(n, 0);
	for (int i = 0; i < n; i++) {
		cin >> x >> y >> c;
		v.push_back({ x,y,c });
	}
	sort(v.begin(), v.end(), compare);

	for (int i = 0; i < n; i++) {
		dp13[i] = dp24[i] = v[i].c;
	}

	int ans = -1;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < i; j++) {
			if (v[j].y < v[i].y) {
				dp13[i] = max(dp13[i], dp13[j] + v[i].c);
			}
			if (v[j].y > v[i].y) {
				dp24[i] = max(dp24[i], dp24[j] + v[i].c);
			}
		}
		ans = max(ans, dp13[i]);
		ans = max(ans, dp24[i]);
	}
	cout << ans;
};