使用排序向量的2-SUM算法

时间:2013-08-06 08:53:18

标签: c++ stl-algorithm

我正在尝试使用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;
}

2 个答案:

答案 0 :(得分:0)

此程序不会要求用户输入以用作't'的值。所以我假设你不想要加起来特定t的x-y对的数量。你的程序会遍历't'的每个可能值,看看是否有一对x-y对加起来,然后转到't'的下一个值。

答案 1 :(得分:0)

我认为你需要在循环通过LOWER到HIGHER之前对数据向量进行排序。因为,必须对数据进行排序,以便将使用x和y实现的算法应用为相反方向的两个迭代器。