题解:P13027 [GCJ 2021 #1A] Prime Time
__coderyc__ · · 题解
题意
你有一些一面上写着质数的牌,你的得分定义为将这组牌分为两组,此时一组牌的和等于另外一组牌的积,此时这个和或积就为你的得分,特别地,如果你无法进行分组,得分为
思路
原本想说枚举子集不可行的,但是有这 有志之人不妨试一试。
无妨,假定时限为
我们检查这个乘积能否被乘出来,再检查剩余的数的和能否相加等于这个积,其实这时候已经跳过许多无关的情况了。
最后记得格式化输出。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll solve() {
int M;
cin >> M;
vector<pair<ll, ll>> cards(M);
ll total_sum = 0;
for (int i = 0; i < M; ++i) {
cin >> cards[i].first >> cards[i].second;
total_sum += cards[i].first * cards[i].second;
}
ll max_score = 0;
for (ll P = total_sum; P >= max(2LL, total_sum - 500*60); --P) {
if (P <= 0) continue;
ll sum = 0;
ll temp_P = P;
bool valid = true;
for (auto &[p, cnt] : cards) {
int used = 0;
while (temp_P % p == 0) {
temp_P /= p;
used++;
}
if (used > cnt) {
valid = false;
break;
}
sum += p * (cnt - used);
}
if (valid && temp_P == 1 && sum == P) {
max_score = P;
break;
}
}
return max_score;
}
int main() {
int T;
cin >> T;
for (int t = 1; t <= T; ++t) {
ll ans = solve();
cout << "Case #" << t << ": " << ans << "\n";
}
return 0;
}