A1048 Find Coins
哈希写法
#include <cstdio>
using namespace std;
int main() {
int coins[1001] = {0}, nn, total, value;
scanf("%d%d", &nn, &total);
for (int i = 0; i < nn; ++i) {
scanf("%d", &value);
coins[value]++;
}
bool ok = false;
for (int i = 1; i <= total / 2; ++i) {
if (coins[i]) {
if (coins[total - i]) {
if (total - i != i || (total - i == i && coins[i] >= 2)) {
printf("%d %d\n", i, total - i);
ok = true;
break;
}
}
}
}
if (!ok)
puts("No Solution");
return 0;
}
排序➕二分
#include <cstdio>
#include <algorithm>
using namespace std;
int main() {
int coins[100010], nn, total, c1 = 0, c2 = 0;
scanf("%d%d", &nn, &total);
for (int i = 0; i < nn; i++)
scanf("%d", &coins[i]);
sort(coins, coins + nn);
for (int i = 0; i < nn - 1; ++i) {
int target = total - coins[i];
int index = lower_bound(coins + i + 1, coins + nn, target) - coins;
if (coins[index] == target) {
c1 = coins[i], c2 = coins[index];
break;
}
}
if (c1 == 0)
puts("No Solution");
else printf("%d %d\n", c1, c2);
return 0;
}
网友评论