我正在尝试使用 C++ 中的排序向量来实现 2-SUM 算法的变体。任务是读入一个包含 10^6 个整数的文件,并计算总和为 t 的不同整数(x 和 y)的数量,其中 t 在区间 [-10000, 10000] 内。我已经在几个测试用例上测试了我的代码,它似乎正在工作,但我没有得到编程任务的正确答案。这是针对 Coursera 算法:设计和分析课程的。因此,此作业不会获得任何官方学分。我会很感激任何帮助。你可以在下面找到我的代码。
/*
* TwoSums.cpp
* Created on: 2013-08-05
*
* Description: Implemented a variant of the 2-SUM algorithm for sums between -10000 and 10000.
* The task was to compute the number of target values t in the interval [-10000,10000]
* (inclusive) such that there are distinct numbers x,y in the input file (./HashInt.txt)
* that satisfy x+y=t. The input file was taken from the Algorithms: Design and Analysis course
* taught by Tim Roughgarden on Coursera.
*
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <set>
#define LOWER -10000
#define HIGHER 10000
using namespace std;
const char* inputfile = "./HashInt.txt";
/*
* Precondition: The inputfile is a file that contains integers, both
* positive and negative. Each line contains an integer.
*
* Postcondition: Every number in the file will be stored in vector V.
*/
int ReadFile(vector<long>& V) {
std::string line;
std::ifstream infile;
infile.open(inputfile);
if(infile.fail())
{
cout << "Problem opening file.";
return -1;
}
while (getline(infile, line)) {
istringstream iss(line);
long a;
iss >> a;
V.push_back(a);
}
return 0;
}
/*
* Precondition: V is a sorted vector of integers
*
* Postcondition: The number of target values (t) in the interval
* [-10000,10000] will be displayed in stdout such that there
* are distinct numbers x,y in the input file that satisfy x+y=t.
*/
void TwoSum (const vector<long>& V) {
vector<long>::iterator x;
vector<long>::iterator y;
unsigned long count = 0;
for (int i = LOWER; i <= HIGHER; ++i) {
x = V.begin();
y = V.end()-1;
while (x != y) {
long sum = *x + *y;
if (sum == i) {
count++;
break;
}
else if(sum < i) {
x+=1;
}
else {
y-=1;
}
}
}
cout << "Count is: " << count << endl;
}
int main () {
// Read integers, store in vector
vector<long>V;
if (ReadFile(V) < 0) return -1;
// Erase duplicate numbers and sort vector
set<long> s;
unsigned long size = V.size();
for( unsigned long i = 0; i < size; ++i ) s.insert( V[i] );
V.assign(s.begin(),s.end() );
// Implement 2-SUM algorithm for numbers between -10000 and 10000
TwoSum(V);
return 0;
}