PAT1048 Find Coins (25 分)
阿新 • • 發佈:2018-12-16
解析
①使用二分查詢
②使用hash
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<unordered_set>
using namespace std;
bool func(const vector<int>& data,int M) {
for (int i = 0; i <data.size()-1; i++) {
if (data[i] + data[data. size()- 1] < M)
continue;
if (binary_search(data.begin() + i + 1, data.end(), M-data[i])) {
printf("%d %d", data[i],M-data[i]);
return true;
}
}
return false;
}
int main()
{
int N, M;
scanf("%d %d", &N, &M);
vector<int> data(N);
for (int i = 0; i < N; i++)
scanf ("%d", &data[i]);
sort(data.begin(), data.end());
if (func(data,M)== false)
printf("No Solution");
}
/*
8 15
1 2 8 7 2 4 11 15
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<unordered_map>
#include<unordered_set>
using namespace std;
int main()
{
int N,M;
scanf("%d %d", &N, &M);
vector<int> data(N);
for (int i = 0; i < N; i++)
scanf("%d", &data[i]);
unordered_map<int, int> Map;
for (auto x : data)
Map[x]++;
unordered_set<int> Set(data.cbegin(), data.cend());
sort(data.begin(), data.end());
bool flag = false;
for (auto x : data) {
if (Set.find(M-x) !=Set.end()) { //OK
if (2*x==M && Map[x]<=1)
continue;
flag = true;
printf("%d %d", x, M - x);
break;
}
}
if (flag == false)
printf("No Solution");
}