problem-solving
boj 1202: 보석도둑
pikkaso
2022. 5. 2. 01:23
https://www.acmicpc.net/problem/1202
1202번: 보석 도둑
첫째 줄에 N과 K가 주어진다. (1 ≤ N, K ≤ 300,000) 다음 N개 줄에는 각 보석의 정보 Mi와 Vi가 주어진다. (0 ≤ Mi, Vi ≤ 1,000,000) 다음 K개 줄에는 가방에 담을 수 있는 최대 무게 Ci가 주어진다. (1 ≤ Ci
www.acmicpc.net
그리디로 pq써서 푸는 문제이다. 앞에서 푼 컵라면하고 비슷하다.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,k;
vector<pair<int,int>> diamond;
vector<int> C;
struct comp{
bool operator()(pair<int,int> &a, pair<int,int> &b){
return a.second < b.second;
}
};
int main(){
cin>>n>>k;
diamond = vector<pair<int,int>>(n);
C = vector<int>(k,0);
for(int i=0;i<n;i++){
cin>>diamond[i].first>>diamond[i].second;
}
for(int i=0;i<k;i++){
cin>>C[i];
}
sort(C.begin(),C.end());
sort(diamond.begin(),diamond.end());
priority_queue<pair<int,int>, vector<pair<int,int>>, comp> pq;
int l=0;
ll ans = 0;
for(int i=0;i<k;i++){
while(l<n){
if(diamond[l].first <= C[i]){
pq.push(diamond[l]);
l++;
}else break;
}
if(pq.size()){
ans += pq.top().second;
pq.pop();
}
}
cout<<ans<<'\n';
return 0;
}
근데 올바르게 접근한거 같은데 아래 코드는 왜 틀리는지 모르겠다.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,k;
vector<pair<int,int>> diamond;
vector<int> C,dia;
struct comp{
bool operator()(pair<int,int> &a, pair<int,int> &b){
return a.second < b.second;
}
};
int main(){
cin>>n>>k;
diamond = vector<pair<int,int>>(n);
C = vector<int>(k,0);
for(int i=0;i<n;i++){
cin>>diamond[i].first>>diamond[i].second;
}
for(int i=0;i<k;i++){
cin>>C[i];
}
sort(C.begin(),C.end());
sort(diamond.begin(),diamond.end());
priority_queue<pair<int,int>, vector<pair<int,int>>, comp> pq;
int l=0, allocate=0;
ll ans = 0;
while(allocate<k){
while(diamond[l].first > C[allocate]){
if(pq.size()){
ans += pq.top().second;
pq.pop();
}
allocate++;
if(allocate == k) break;
}
if(allocate == k) break;
pq.push(diamond[l]);
l++;
if(l==n){
while(!pq.empty()){
ans += pq.top().second;
pq.pop();
allocate++;
if(allocate == k) break;
}
}
}
/*
if(pq.size()){
ans += pq.top().second;
pq.pop();
}
*/
cout<<ans<<'\n';
return 0;
}