Kattis题目CD提交错误求助:本地测试正确但提交判错
Hey everyone! I’m working on solving the CD problem over on Kattis. I’ve tested my code with all the cases I can think of locally and it gives the right results every time, but when I submit it, I keep getting a Wrong Answer. I’m really confused about where I’m going wrong—could anyone take a look at my code and point out the issue?
Here’s a screenshot of the problem for reference:
And this is my Java code:
import java.util.*; public class Kattis { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); while(n != 0 || m!=0) { boolean[] ar1 = new boolean[1000000]; int count = 0; for(int i = 0; i < n+m;i++) { int num = sc.nextInt(); if(ar1[num]) { count++; } else { ar1[num] = true; } } System.out.println(count); n = sc.nextInt(); m = sc.nextInt(); } sc.close(); } }
The Root of the Problem
Let me break down what’s going wrong here. The problem asks for the number of unique CDs that appear in both Jack’s and Jill’s collections—but your current code counts every duplicate occurrence across all n+m entries, not unique overlapping CDs.
For example:
- If Jack has CD 123 once, and Jill has CD 123 twice, your code would increment the count twice (once for each of Jill’s copies). But the correct answer should be 1, since it’s the same unique CD present in both collections.
Fixed Approach
We need to track unique CDs from one collection, then check how many unique CDs from the second collection overlap with it. Here’s the corrected code:
import java.util.*; public class Kattis { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); while(n != 0 || m!=0) { Set<Integer> jacksCDs = new HashSet<>(); int count = 0; // Add all of Jack's unique CDs to the set for(int i = 0; i < n; i++) { jacksCDs.add(sc.nextInt()); } // Check Jill's CDs against Jack's unique set for(int i = 0; i < m; i++) { int cd = sc.nextInt(); if(jacksCDs.contains(cd)) { count++; jacksCDs.remove(cd); // Prevent counting duplicates in Jill's list } } System.out.println(count); n = sc.nextInt(); m = sc.nextInt(); } sc.close(); } }
Why This Works
- We use a
HashSetto store Jack’s CDs, which automatically handles duplicates (so only unique CDs are kept). - When iterating through Jill’s CDs, we check if the CD exists in Jack’s set. If it does, we increment the count and remove the CD from the set—this ensures we only count each unique overlapping CD once, even if Jill has multiple copies.
Your local test cases probably didn’t include scenarios with duplicate CDs in one of the collections, which is why the code worked locally but failed Kattis’s test cases. This fix should resolve the Wrong Answer issue!
内容的提问来源于stack exchange,提问作者Eric

