HackerRank Ice Cream Parlor

传送门

Ice Cream Parlor

Authored by dheeraj on Mar 21 2013

Problem Statement

Sunny and Johnny together have M dollars they want to spend on ice cream. The parlor offers N flavors, and they want to choose two flavors so that they end up spending the whole amount.

You are given the cost of these flavors. The cost of the ith flavor is denoted by ci. You have to display the indices of the two flavors whose sum is M.

Input Format

The first line of the input contains TT test cases follow. 
Each test case follows the format detailed below: The first line contains M. The second line contains N. The third line contains N space-separated integers denoting the price of each flavor. Here, the ith integer denotes ci.

Output Format

Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from 1 to N.

Constraints

1T50 
2M10000 
2N10000 
1ci 10000,where i[1,N] 
The prices of any two items may be the same and each test case has a unique solution.

Sample Input

2
4
5
1 4 5 3 2
4
4
2 2 4 3

Sample Output

1 4
1 2

Explanation

The sample input has two test cases. 
For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sum up to 4. 
For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sum up to 4.

Solution

简单题。

利用题目给出的cost数组构造index数组,index[i]表示icost数组中首次出现的位置。

Implementation

 

#include<bits/stdc++.h>
using namespace std;
const int N(1e4+5);
int idx[N];
int main(){
	freopen("in", "r", stdin);
	int T; 
	cin>>T;
	for(int n, m, id1, id2; T--; memset(idx, 0, sizeof(idx))){
		cin>>m>>n;
		for(int i=1, c; i<=n; i++){
			cin>>c;
			if(c>=m) continue;	//error-prone
			if(!idx[c]) idx[c]=i;
			if(idx[m-c]&&idx[m-c]!=i){
				id1=idx[m-c], id2=i;	//error-prone
			}
		}
		cout<<id1<<' '<<id2<<endl;
	}
}

凡注释error-prone的地方都是开始写错了的。

1. 我的写法是边读入边处理的,有时会没读完就得出答案,这时很容易就来个break;

2. 针对这道题的

  2.1 要预判c>=m的情况

  2.2 如何处理cost相同的flavor

转载于:https://www.cnblogs.com/Patt/p/4746518.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值