在线评委如何传递输入数据?

时间:2018-04-07 18:03:41

标签: c++

我正试图通过在线评委(Codeforces)来解决这个问题:

  

有一天,Deivis遇到了两个整数A和B的向量,并想知道,是否可以通过将A的元素添加到B的另一个元素来形成数字X?

     

更正式地说,可以选择两个索引i和j,使Ai + Bj = x?

     

输入
  第一个输入行是两个整数n和x。第二行包含n个数字,即向量A.第三行和最后一行包含n个数字,向量B。

     

输出
  如果可以从每个向量的一个元素的总和形成数字x,则打印1,否则为0。“

我的问题是我无法填写第二个向量,当程序在网站上运行时,它用零填充向量。我正在使用C ++,这是我的代码:

#include <bits/stdc++.h>

using namespace std;

#define MAX 10

int main()
{
    int n, x, i = 0, j = 0, resp = 0, sum;

    vector<int> vetA(MAX), vetB(MAX);

    cin >> n >> x;

    while (scanf("%d", &vetA[i]) == 1)
        i++;

    while (scanf("%d", &vetB[j]) == 1)
        j++;

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            sum = vetA[i] + vetB[j];
            if (sum == x)
            {
                resp = 1;
                goto END;
            }
        }
    }

    END: printf("%d", resp);

    return 0;
}

我尝试在每个getchar()循环后使用while,但似乎在网站上它不像键盘上那样进行数据捕获,因此第二个向量没有接收任何数据。我也尝试将数据捕获为std::string,但这不起作用。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

以下是将您的计划与以下内容进行比较的一些提示/示例:

#include <iostream> //Include each standard library seperately
#include <vector> //#include <bits/stdc++.h> is bad practice

// Only declare variables as they are used. 
int n; // Better coding practice is one variable per line.
int x; // Competitions shouldn't care how many lines.

if (!(std::cin >> n >> x)) //This is basically the same as cin.fail()
{
  std::cerr << "Error inputting data.\n";
  return 1;
}

// Now create the vectors, after the size has read in.
std::vector<int> vetA(n);
std::vector<int> vetB(n);

// The number of elements is known, so use a "for" loop.
for (size_t i = 0; i < n; ++i)
{
  std::cin >> vetA[i];
}

for (size_t i = 0; i < x; ++i)
{
  std::cin >> vetB[i];
}

您应该添加一些错误处理,因为您的程序将被赋予一些无效的输入。

输入和矢量大小是示例,因为您没有在帖子中指定输入格式。