P15444 题解
赛时很好想到这个地方最小值肯定是 ,唯一我当时的纠结点就是这里可不可能要除多次才能得到这个结果?
在我犹豫是否用 ST 表+贪心时,dalao__luo2031__ 已经 AC。当时就直接打了个除一次的解法上去,对了。当时没细想赛后还是证明出来了。
证明过程
为何选除数和被除数分别为最小最大值
下图是除数和被除数随大小变化的图像(也就是函数 的图像):
显然, 越靠右越小, 越靠正方向越小。所以如何选择就是顺理成章的了。
或者符号推导一下,根据不等式的性质,如果 ,那么 。所以最小的肯定是被除数(除非不操作)。
然后我们知道被除数一定,除数和商是反比例关系。所以我们让商尽可能小的做法就是让除数尽可能大。故除数肯定是最大的。
为何只用除一次
当我们对整个序列 时,我们可以保证所有数都 ,故如果再继续操作就不可能带来收益。所以只需要除一次最大值即可。
为何不用多次非最大值除最小值
首先我们假定这个值为 ,那么首轮操作后最小值变为 ,然后下一轮我们选择上一个数 。这个数现在是 。那么这个式子变成 。相当于 ,相当于除了一个 。如果再来一次操作选择数 也是一个道理,那个非最后一次除的数都会约掉,所以这也非最优。
想到解法后因为我代码固有的大常数和猎奇码风第一发 long long 交上去只有 1 个点。逐花巨量时间改成 __int128 解法 AC。(你可能会说:改 __int128 不是改下输出就行了吗?但是我当时重载的输入输出,故只能使用 std::istream 和 std::ostream 的功能实现。)
接下来奉上我 134 行的猎奇代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
__int128 gcd(__int128 x, __int128 y) {
while (y) {
__int128 t = x%y;
x = y;
y = t;
}
return x;
}
__int128 Abs(__int128 x) {
if (x < 0)
return -x;
else
return x;
}
struct num {
__int128 x, y;
friend istream& operator>>(istream& is, num& tmp) {
while (isspace(is.peek())) is.get();
__int128 fact = 1;
__int128 abso = 0;
if (is.peek() == '-')
fact = -1, is.get();
char c = 0 ;
while (isdigit(c = is.get())) {
abso *= 10;
abso += (c-'0');
}
tmp.x = abso*fact;
while (isspace(is.peek())) is.get();
fact = 1;
abso = 0;
if (is.peek() == '-')
fact = -1, is.get();
c = 0;
while (isdigit(c = is.get())) {
abso *= 10;
abso += (c-'0');
}
tmp.y = abso*fact;
return is;
}
friend ostream& operator<<(ostream& os, num& tmp) {
if (tmp.x < 0)
os << '-';
__int128 cur = Abs(tmp.x);
string out = "";
stringstream ss;
while (cur > 0) {
ss << (char)('0' + (cur % 10));
cur /= 10;
}
out = ss.str();
ss.str("");
reverse(out.begin(), out.end());
os << out << ' ';
if (tmp.y < 0)
os << '-';
cur = Abs(tmp.y);
out = "";
while (cur > 0) {
ss << (char)('0' + (cur % 10));
cur /= 10;
}
out = ss.str();
reverse(out.begin(), out.end());
os << out << '\n';
return os;
}
bool operator>(const num& k) const {
__int128 nm = (y*k.y)/(gcd(k.y, y));
__int128 c1 = (nm/y)*x,
c2 = (nm/k.y)*k.x;
return c1>c2;
}
bool operator<(const num& k) const {
__int128 nm = (y*k.y)/(gcd(k.y, y));
__int128 c1 = (nm/y)*x,
c2 = (nm/k.y)*k.x;
return c1<c2;
}
num operator+(num k) {
__int128 nm = (y*k.y)/(gcd(k.y, y));
__int128 c1 = (nm/y)*x,
c2 = (nm/k.y)*k.x;
return {c1+c2, nm};
}
num operator-(num k) {
__int128 nm = (y*k.y)/(gcd(k.y, y));
__int128 c1 = (nm/y)*x,
c2 = (nm/k.y)*k.x;
return {c1-c2, nm};
}
num operator*(num k) {
num res = {k.x*x, k.y*y};
__int128 g = gcd(res.x, res.y);
res.x /= g;
res.y /= g;
return res;
}
num operator/(num k) {
num res = {k.y*x, k.x*y};
__int128 g = gcd(res.x, res.y);
res.x /= g;
res.y /= g;
return res;
}
};
int n;
num a[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
num a1 = *(max_element(a+1, a+n+1));
num a2 = *(min_element(a+1, a+n+1));
num res = a2/a1;
if (res < a1) //有的时候不操作是更加优秀的
cout << res;
else
cout << a1;
return 0;
}