题目
1048 Find Coins (25 分)
Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 105 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (≤105, the total number of coins) and M (≤103, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the two face values V1 and V2 (separated by a space) such that V1+V2=M and V1≤V2. If such a solution is not unique, output the one with the smallest V1. If there is no solution, output No Solution instead.
Sample Input 1:
8 15
1 2 8 7 2 4 11 15
Sample Output 1:
4 11
Sample Input 2:
7 14
1 8 7 2 4 11 15
Sample Output 2:
No Solution
原题:: A1048.
题解
此题的做法有多种,有散列法、二分查找法等,现说一下散列法思路:
先输入n、m,然后输入n个数,从n个数中找两个数相加等于m的输出,如果有多组,则输出第一个数最小的答案,如果没有符合条件的数对存在输出No Solution。
首先建立一个数组来保存输入的数出现的个数比如1 2 8 7 2 4 11 15这个数列存入hashTable[]中,则hashTable[1]=1,hashTable[2]=2,hashTable[4]=1…
然后在hashTable里寻找相加和等于m的数对。需要注意的点是如果两个数相等的话还需要判断hashTable[]的数是否大于等于2,如果不符合则不行
代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,a,hashTable[10010]={0};
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>a;
hashTable[a]++;
}
for(int i=1;i<m;i++){
if(hashTable[i] && hashTable[m-i]){
if(i==m-i && hashTable[i]<=1)continue;
printf("%d %d",i,m-i);
return 0;
}
}
printf("No Solution");
}
第二种方法是二分查找法,思路是先对输入的数列排序,然后从小到大查找符合条件的两个数对。如果使用选择查找的话时间复杂度为10^10太大,所以可以在查找的地方使用二分查找来减少时间复杂度