Each layer costs money and effort, so a security team wants the fewest layers that bring the risk under a target.
What to build
Choose the fewest layers whose combined effect lets through at most T attacks in 10000.
Requirements
- Layers fail independently, so a set of layers lets through the product of (100 − stop)% of attacks.
- Find the smallest number of layers that lets through at most T in 10000. (Taking the strongest layers first is always enough, because for a fixed number of layers the strongest ones give the smallest product.)
- Print the chosen layer names, strongest first, one per line. Equal stop rates keep their input order.
- Then print
lets through X in 10000, with X to 2 decimal places. If no layer is needed (T is 10000), print only this line. - If even all the layers together are not enough, print
cannot reach the target.
Input
Line 1: T, a whole number. Each following line: a layer name (no spaces) and its stop rate, a whole percentage.
Output
As described.
Constraints
T is 0 to 10000. 1 to 8 layers.
Example
Input:
5
filter 90
training 60
2fa 99
Output:
2fa
filter
training
lets through 4.00 in 10000
Why it works
For any fixed count k, the k strongest layers give the smallest product, so trying k = 1, 2, 3 ... with the strongest layers finds the fewest that work. Comparing whole numbers, product of (100 − stop) × 10000 ≤ T × 100^k, avoids rounding errors at the boundary.
Examples
5 filter 90 training 60 2fa 99
2fa filter training lets through 4.00 in 10000
100 firewall 80 antivirus 50
cannot reach the target
Hints
Hint 1
Sort a copy of the layers by stop rate, highest first; JavaScript's sort keeps equal items in their order.
Hint 2
Use BigInt for the exact comparison: the products grow up to 100^8.
Hint 3
When T is 10000, no layer is needed: print only the summary line.
Solution
Show one correct solution (try it yourself first)
const target = Number(prompt());
const layers = [];
let line = prompt();
while (line !== null) {
const [name, stop] = line.trim().split(/\s+/);
layers.push({ name, stop: Number(stop) });
line = prompt();
}
layers.sort((a, b) => b.stop - a.stop);
let product = 1n;
let found = -1;
if (10000n <= BigInt(target)) found = 0;
for (let k = 1; k <= layers.length && found < 0; k++) {
product *= BigInt(100 - layers[k - 1].stop);
if (product * 10000n <= BigInt(target) * 100n ** BigInt(k)) found = k;
}
if (found < 0) console.log("cannot reach the target");
else {
let through = 10000;
for (let k = 0; k < found; k++) {
console.log(layers[k].name);
through *= (100 - layers[k].stop) / 100;
}
console.log(`lets through ${through.toFixed(2)} in 10000`);
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step