AtCoder Beginner Contest C - Robot Factory
問題はこちら
回答
素直な総当たりではO(N M)となり、TLE
Biが大きいほど、たくさんのHiをカバーできることに着目
大きいBiから見て行き、Hi<=Biを満たすHiの中から、最も大きいHiを貪欲に採用していけばいい
BiをインプットにHiの配列に対して二分探索を行っている
この時、ソート後のHiの先頭にはBiのどれよりも小さい値、末尾にはBiのどれよりも大きい値を入れている
また、一度選択されたHiがもう一度選択されないように、一度選択されたHiには大きな値を加算し、Biのどれよりも大きくなるようにしている
計算量はO(M logM) + O(M logN) + O(N logM)
#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <limits.h>
#include <bitset>
#include <list>
#include <set>
#include <numeric>
#include <tuple>
int N, M, K;
std::vector<long long> H;
std::vector<long long> B;
long long inf = 1000000001;
int main()
{
std::cin.tie(0);
std::ios::sync_with_stdio(false);
std::cin >> N >> M >> K;
H.push_back(0); // Bのどの値よりも小さくなる数値
for (int i = 0; i < N; i++) {
long long h;
std::cin >> h;
H.push_back(h);
}
H.push_back(LLONG_MAX); // 番兵
for (int i = 0; i < M; i++) {
long long b;
std::cin >> b;
B.push_back(b);
}
std::sort(H.begin(), H.end());
std::sort(B.begin(), B.end(), std::greater<long long>());
// B>=Hである必要
int count = 0;
for (const long long& b : B) {
// 初めてbより大きくなるHのインデックスを算出
int idx = std::upper_bound(H.begin(), H.end(), b) - H.begin();
if (idx-1 == 0) {
break;
}
else {
H[idx-1] += inf;
count++;
}
}
if (count < K) {
std::cout << "No" << std::endl;
}
else {
std::cout << "Yes" << std::endl;
}
return 0;
}
公式回答
K体作れるかだけを判定するなら、
H の軽い方からK個
B の重い方からK個
だけを考えれば十分
「K個作れるか」という判定問題に限定して、さらに問題を簡略化した方法
頭:軽いほど有利
→ 軽い方からK個だけ見ればいい
体:重いほど有利
→ 重い方からK個だけ見ればいい
と考えから着想可能
sort(H.begin(), H.end());
sort(B.begin(), B.end());
for (int i = 0; i < K; i++) {
if (H[i] > B[M - K + i]) {
cout << "No\n";
return 0;
}
}
cout << "Yes\n";
2回目に解いた時の解答
#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <limits.h>
#include <bitset>
#include <list>
#include <set>
#include <numeric>
#include <tuple>
int N,M,K;
std::vector<long long> H;
std::vector<long long> B;
int main()
{
std::cin.tie(0);
std::ios::sync_with_stdio(false);
std::cin >> N >> M >> K;
for (int i = 0; i < N; i++) {
long long h;
std::cin >> h;
H.push_back(h);
}
for (int i = 0; i < M; i++) {
long long b;
std::cin >> b;
B.push_back(b);
}
// h<=bであればいい
// hに対して、上記を満たすギリギリのbをとっていく
std::sort(H.begin(), H.end());
std::sort(B.begin(), B.end());
int count = 0;
auto bPtr = B.begin();
for (int i = 0; i < N; i++) {
int hVal = H[i];
auto ptr = std::lower_bound(bPtr, B.end(), hVal);
if (ptr == B.end()) {
break;
}
else {
count++;
}
int pos = ptr - bPtr;
bPtr += (pos + 1);
}
if (count >= K) {
std::cout << "Yes" << std::endl;
}
else {
std::cout << "No" << std::endl;
}
return 0;
}