【Google Code Jam】Problem A. Store Credit

Problem here

Problem

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

Small dataset

N = 10
3 ≤ I ≤ 100

Large dataset

N = 50
3 ≤ I ≤ 2000

Sample

Input

3
100
3
5 75 25
200
7
150 24 79 50 88 345 3
8
8
2 1 9 4 4 56 90 3

Output

Case #1: 2 3
Case #2: 1 4
Case #3: 4 5

Solution

直接暴力解決

#include <iostream>
#include <algorithm>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
using namespace std;

int main(){
    ifstream fin("A-large-practice.in");    //ifstream fin("A-small-practice.in");
    ofstream fout("A-large-practice.out");  //ofstream fout("A-small-practice.out");
    int n;
    fin >> n;
    for(int cnt = 1; cnt <= n; cnt++){        
        int bg;
        fin >> bg;
        int len;
        fin >> len;
        vector<int> nums;
        for(int i = 0; i < len; i++){
            int tmp;
            fin >> tmp;
            nums.push_back(tmp);
        }
        int ansX, ansY;

        for(int i = len-1; i >= 0; i--){
            for(int j = 0; j < len; j++){
                if(i != j && nums[i] < bg && nums[j] < bg){
                    if(nums[i] + nums[j] == bg){
                        ansX = i;
                        ansY = j;
                    }
                }
            }
        }
        if(ansX > ansY){
            int tmp = ansX;
            ansX = ansY;
            ansY = tmp;
        }
        fout << "Case #" << cnt << ": ";
        fout << ansX+1 << " " << ansY+1 << endl;

    }

    return 0;
}

你可能感兴趣的:(算法,Codejam)