看到这个题第一反应还是暴力求解,但是当硬币的数量增长到很多时,运行会超时!!!用二分查找可以有效缩短时间!
解法一:(20分,有两个样例是超时的)
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int a[maxn];
int main()
{
int n, m;
bool flag = false;
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++)
{
scanf("%d", &a[i]);
}
sort(a, a+n);//排序
for(int i = 0; i < n; i ++)
{
for(int j = i + 1; j < n; j ++)
{
if(a[i] + a[j] == m)
{
flag = true;
printf("%d %d\n", a[i], a[j]);
i = j = n;
break;
}
}
}
if(!flag) printf("No Solution\n");
return 0;
}
解法二:(25分)
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int a[maxn];
int Binary_Search(int left, int right, int key)//二分查找
{
int mid;
while(left <= right)
{
mid = (left + right) / 2;
if(key == a[mid]) return mid;
else if(key < a[mid]) right = mid - 1;
else left = mid + 1;
}
return -1;//若未找到,则返回-1
}
int main()
{
int n, m, i;
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++)
{
scanf("%d", &a[i]);
}
sort(a, a + n);//对数组进行排序
for(i = 0; i < n; i ++)
{
int ans = Binary_Search(0, n-1, m-a[i]);
if(ans != -1 && ans != i)//若找到
{
printf("%d %d\n", a[i], a[ans]);
break;
}
}
if(i == n) printf("No Solution");
return 0;
}