跳到正文

题解

2024 xyd 集训 Day 1 贪心 随堂练习 T4 题解

残阳如血约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v1当前

Description\textbf{Description}

有 n+1n+1 个二元组 (ai,bi)(a_i,b_i) 有序排成一个序列(从 00 开始编号)。

第 ii 个二元组的权值为

⌊∏j=0i−1ajbi⌋\Bigg\lfloor\dfrac{\prod\limits_{j=0}^{i-1}a_j}{b_i}\Bigg\rfloor

现在可以任意排列第 1∼n1\sim n 个二元组的位置,要求最小化所有权值中的最大值。

Solution\textbf{Solution}

PS:分析时暂时忽略向下取整。

假设最终的结果状态的第 ii 位为 (ai,bi)(a_i,b_i),第 i+1i+1 位为 (ai+1,bi+1)(a_{i+1},b_{i+1})​。

设 x=∏j=0i−1ajx=\prod\limits_{j=0}^{i-1}a_j,即 0∼i−10\sim i-1 中 aa 的前缀积。

  • 交换前
    • 第 ii 个二元组的权值:xbi\dfrac{x}{b_i}。
    • 第 i+1i+1 个二元组的权值:x×aibi+1\dfrac{x\times a_i}{b_{i+1}}。
  • 交换后
    • 第 ii 个二元组的权值:xbi+1\dfrac{x}{b_{i+1}}。
    • 第 i+1i+1 个二元组的权值:x×ai+1bi\dfrac{x\times a_{i+1}}{b_i}​。

由于最终结果应该是最优的,故:

max⁡{xbi,x×aibi+1}≤max⁡{xbi+1,x×ai+1bi}\max\Big\{\dfrac{x}{b_i},\dfrac{x\times a_i}{b_{i+1}}\Big\}\le\max\Big\{\dfrac{x}{b_{i+1}},\dfrac{x\times a_{i+1}}{b_i}\Big\}

两边同时约去 xx,得:

max⁡{1bi,aibi+1}≤max⁡{1bi+1,ai+1bi}\max\Big\{\dfrac{1}{b_i},\dfrac{a_i}{b_{i+1}}\Big\}\le\max\Big\{\dfrac{1}{b_{i+1}},\dfrac{a_{i+1}}{b_i}\Big\}

两边同时乘上 bi×bi+1b_i\times b_{i+1},消去分母,得:

max⁡{bi+1,ai×bi}≤max⁡{bi,ai+1×bi+1}\max\{b_{i+1},a_i\times b_i\}\le\max\{b_i,a_{i+1}\times b_{i+1}\}

故按照如此规则排序即可。

Code\textbf{Code}

C++
#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;
}
原文