【问题标题】:3n+1 uVa gives WA [closed]3n+1 uVa 给出 WA [关闭]
【发布时间】:2016-08-29 19:32:29
【问题描述】:

我最初的问题有点含糊,所以这是经过编辑的问题。

3n+1 uVa 问题基于 Collat​​z 猜想。 考虑任何正整数“n”。如果是偶数,则除以 2。如果是奇数,则将其乘以 3 并加 1。经过 'x' 这样的重复操作,你将得到 1。这已经被超级计算机证明了非常大的数字。

UVa Online Judge 是由巴利亚多利德大学主办的针对编程问题的在线自动裁判。

这是问题陈述的链接: uVa 3n+1

请在查看我的代码之前阅读问题说明! uVa 在线法官针对某些测试用例运行您的代码,并告诉您您的解决方案是对还是错。它不会告诉您失败的原因(如果您的解决方案错误)。

如果您错过了第一个链接,请再次查看链接: The link to the problem description

我不明白我在代码逻辑中遗漏或跳过了什么(因为我得到了错误的答案)。我已经尝试了很多测试用例,它们似乎工作正常。我知道逻辑可以在很大程度上被压缩,但我现在只需要弄清楚缺陷在哪里。

这是我的代码。我知道不应该使用 bits/stdc++,但目前,它不会影响我的代码。如果可以,请查看并帮助我。

#include<iostream>
#include<cstdlib>
#include<bits/stdc++.h>
using namespace std;

int main()
{
unsigned long int num;
int i,j,tempi, tempj,temp;

//Scanning until inputs don't stop
while(scanf("%d %d",&i,&j)!=EOF)
{
//Boolean variable to set if i is greater
bool iwasmore=false;
//Boolean variable for equal numbers
bool equalnums=false;
int cycles=1, maxcycles=0;

if(i>j)
{
//swapping for the for loop to follow
temp=i; i=j; j=temp;
iwasmore=true;
}

if(i==j)
{
    equalnums=true;
}

tempi=i; tempj=j;   

//Taking each number in the given range and running it in the algorithm.
//The maxcycles variable will have the value of the maximum number of cycles
//that one of the numbers in the range took (at the end of the for loop).
for(num=i;num<=j;num=(++tempi))
{
if(cycles>maxcycles)
{
    maxcycles=cycles;
}
cycles=1;
//The actual algorithm
while(num!=1)
    {
        if(num%2==1)
        {
        num = (3*num)+1;
        cycles++;
        }

        else
        {
        num=(num/2);
        cycles++;
        }
    }

    if(equalnums==true)
        {
            maxcycles=cycles;
            equalnums=false;
        }
//Resetting num
    num=0;
}
if(!iwasmore)
cout<<i<<" "<<j<<" "<<maxcycles<<endl;
else
cout<<j<<" "<<i<<" "<<maxcycles<<endl;
}
return 0;
}

这是我为以下输入得到的输出:

输入:

1 1

10 1

210 201

113383 113383

999999 1

输出:

1 1 1

10 1 20

210 201 89

113383 113383 248

999999 1 525

另一个测试用例:

输入:

1 5

10 8

210 202

113383 113383

999999 999989

输出:

1 5 8

10 8 20

210 202 89

113383 113383 248

999999 999989 259

【问题讨论】:

  • 您缺少或跳过了正确的问题描述。 uVa 是什么? WA 是什么?你想做什么?什么不起作用?
  • 你好。我已经给出了问题描述的链接(这里复制粘贴太长了)。Problem Statement
  • 如果输入是1 1,你的程序会输出什么?
  • @SaunvedMutalik SO 不需要链接或复制粘贴,而是需要您的描述。
  • 顺便说一句,#include&lt;bits/stdc++.h&gt; 不好。

标签: c++ collatz


【解决方案1】:

最后检查的数字的循环长度永远不会与最大值进行比较。

对于输入:

8 9
9 9

程序输出

8 9 4
9 9 20

但正确答案是

8 9 20
9 9 20

if (cycles > maxcycles) {
    maxcycles = cycles;
}

在 for 循环的末尾,而不是在开头。

【讨论】:

  • 我很确定我在其他程序中也犯过这个错误!终于找到了解决办法。谢谢!现在代码被接受了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多