Skip to content

Instantly share code, notes, and snippets.

@lishunan246
Created December 7, 2016 17:56
Show Gist options
  • Save lishunan246/a8c46cbfc0f62a92950161e56eeee563 to your computer and use it in GitHub Desktop.
Save lishunan246/a8c46cbfc0f62a92950161e56eeee563 to your computer and use it in GitHub Desktop.
two sum
#include <fstream>
#include <iostream>
#include <unordered_set>
#include <thread>
#include <future>
int foo(long long a, long long b, const std::unordered_set<long long>& set)
{
int result(0);
for (auto i = a; i < b; ++i)
{
for (auto&& n : set)
{
if (set.find(i - n) != set.end())
{
result++;
break;
}
}
}
std::cout << result << std::endl;
return result;
}
int main()
{
auto thread_cnt = std::thread::hardware_concurrency();
std::ifstream input_file("D:\\Playground\\2sum.txt");
long long t;
std::unordered_set<long long> set;
while (input_file >> t)
{
set.insert(t);
}
auto m = -10000, n = 10000;
std::vector<std::future<int>> fut;
int d = (n - m) / thread_cnt;
for (auto i = 0; i < thread_cnt; i++)
{
fut.push_back(std::async(foo, m, m + d, set));
std::cout << m << " " << m + d << std::endl;
m += d;
}
int r = 0;
for (auto&& f:fut)
{
r += f.get();
}
for (auto&& x : set)
{
if (set.find(n - x) != set.end())
{
r++;
break;
}
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment