UVA在线评判3n + 1:错误答案

时间:2015-01-15 06:12:44

标签: c++ algorithm visual-c++

我一直在研究这个问题,但是每次提交它都会得到错误的答案,但是当我输入样本案例时,我似乎得到了正确的答案。谁能帮到我这里? 问题可以在这个网站上找到:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=36

代码本身:

#include <vector>
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;

long find_cycle_length(long b)
{
    // Finds the max cycle of b
    long max_cycle = 1;
    while (b != 1)
    {
        if (b % 2 != 0)
        {
            b = (3 * b) + 1;
            ++max_cycle;
        }
        else if (b % 2 == 0)
        {
            b /= 2;
            ++max_cycle;
        }
    }
    return max_cycle;
}
long find_max_cycle(vector <long>& b)
{
    vector <long> temp;
    for (int i = 0; i < b.size(); ++i)
    {
        long buffer = b[i];
        temp.push_back(find_cycle_length(buffer));
    }
    long max_cycle = *max_element(temp.begin(), temp.end());

    return max_cycle;
}

int main()
{
        long i = 0; // First number
        long j = 0; // Second number
        long size = 0; // Determines the size of the vector buffer
        long counter = 0; // Used to fill buffer
        cin >> i >> j;


        if (j > i) {
            size = (j - i) + 1;
            counter = i;
        }
        else if (i > j) {
            size = (i - j) + 1;
            counter = j;
        }
        else if (i == j)
        {
            size = 1;
            counter = i;
        }

        vector<long> buffer(size); // Used to store all numbers i to j  
        for (int x = 0; x < buffer.size(); ++x) // fill buffer
        {
            buffer[x] = counter;
            ++counter;
        }

        cout << i << " " << j << " " << find_max_cycle(buffer) << endl;

        return 0;

}

1 个答案:

答案 0 :(得分:0)

我认为你可能误解了这些指示。样本输入不是

1 10

1 10
100 200
201 210
900 1000

你没有一个允许用户为你提供多行输入的while循环 - 你的程序在一个循环之后退出。你为什么不进行这种改变 - 让用户继续输入新的输入行直到给你一个文件结尾(或者 - 它编码同样用于编码 - 接受来自输入的所有输入行文件重定向到标准输入) - 看看你是否正常?

哦,我看到molbdnilo在第一条评论中提出这一点。无论如何:他是对的。

相关问题