Problem Links:
Google Code Jam.Problem:
Problem Store Credit
You receive a credit
C
at a local store and would like to buy two items. You first walk through the store and create a list L
of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).
Input
The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:
- One line containing the value C, the amount of credit you have at the store.
- One line containing the value I, the number of items in the store.
- One line containing a space separated list of I integers. Each integer P indicates the price of an item in the store.
- Each test case will have exactly one solution.
Output
For each test case, output one line containing "Case #x: " followed by the indices of the two items whose price adds up to the store credit. The lower index should be output first.
Limits
5 ≤ C ≤ 1000
1 ≤ P ≤ 1000
1 ≤ P ≤ 1000
Small dataset
N = 10
3 ≤ I ≤ 100
3 ≤ I ≤ 100
Large dataset
N = 50
3 ≤ I ≤ 2000
3 ≤ I ≤ 2000
Sample
Solution:
Ad-hoc.Source Code:
/** * */ package com.googlecodejam.yr2010.africa.qualification; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; /** * @author antonio081014 * @time May 3, 2013, 9:46:01 PM */ public class A { public static void main(String[] args) throws Exception { A main = new A(); main.run(); System.exit(0); } private void run() throws Exception { BufferedReader in = new BufferedReader(new FileReader("input.in")); PrintWriter out = new PrintWriter(new FileWriter("output.txt")); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; t++) { out.write("Case #" + t + ": "); int Value = Integer.parseInt(in.readLine()); int N = Integer.parseInt(in.readLine()); int[] board = new int[N]; String[] str = in.readLine().split("\\s"); for (int i = 0; i < N; i++) board[i] = Integer.parseInt(str[i]); out.write(solve(board, Value) + "\n"); } in.close(); out.close(); } private String solve(int[] board, int value) { for (int i = 0; i < board.length; i++) { for (int j = i + 1; j < board.length; j++) { if (board[i] + board[j] == value) { return String.format("%d %d", i + 1, j + 1); } } } return null; } }
No comments :
Post a Comment