2024 xyd 集训 Day 1 贪心 随堂练习 T4 题解
\textbf{Description}
有
第
现在可以任意排列第
\textbf{Solution}
PS:分析时暂时忽略向下取整。
假设最终的结果状态的第
设
- 交换前
- 第
i 个二元组的权值:\dfrac{x}{b_i} 。 - 第
i+1 个二元组的权值:\dfrac{x\times a_i}{b_{i+1}} 。
- 第
- 交换后
- 第
i 个二元组的权值:\dfrac{x}{b_{i+1}} 。 - 第
i+1 个二元组的权值:\dfrac{x\times a_{i+1}}{b_i} 。
- 第
由于最终结果应该是最优的,故:
两边同时约去
两边同时乘上
故按照如此规则排序即可。
\textbf{Code}
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#define max(a,b) ((a)>(b)?(a):(b))
const int N = 1e3 + 10;
struct Data {
int a, b;
std::string num; // 存储其权值
bool operator<(const Data &p) const {
return max(p.b, a * b) < max(b, p.a * p.b);
}
} t[N];
int n;
std::string ans = "0";
void init(const std::string &s, std::vector<int> &num) { // 将 s 倒序存入 num 中
num.resize(s.size());
for (size_t i = 0; i < s.size(); ++i)
num[i] = s[s.size() - i - 1] - '0';
}
std::string get(std::vector<int> &ans) { // 将一个倒序存储的 vector 转化为正序存储的字符串
while (ans.size() > 1 && ans.back() == 0) ans.pop_back();
std::string res;
for (long long i = ans.size() - 1; ~i; --i)
res.push_back(ans[i] + '0');
return res;
}
std::string operator*(const std::string &sa, int b); // 高精乘单精
std::string operator/(const std::string &sa, int b); // 高精除单精
int cmp(const std::string &a, const std::string &b) { // 大小判断
// 0:a=b 1:a>b -1:a<b
if (a.size() != b.size())
return a.size() > b.size() ? 1 : -1;
for (size_t i = 0; i < a.size(); ++i) {
if (a[i] > b[i]) return 1;
if (a[i] < b[i]) return -1;
}
return 0;
}
int main() {
std::cin.tie(0)->sync_with_stdio(0);
std::cin >> n;
for (int i = 0; i <= n; ++i) std::cin >> t[i].a >> t[i].b;
std::sort(t + 1, t + n + 1);
std::string mul = std::to_string(t[0].a); // 记录前缀积
for (int i = 1; i <= n; ++i) {
t[i].num = mul / t[i].b;
mul = mul * t[i].a;
if (cmp(ans, t[i].num) == -1) ans = t[i].num;
}
std::cout << ans << std::endl;
return 0;
}