使得没有两个元素相邻的最大和.如何设置约束



黑客问题:

到目前为止,XYZ国家尚未发现新冠肺炎病例。那里的科学家和研究人员进行了一项研究,发现在一条有房子的街道上(假设房子只在街道的一侧,另一侧是空的(,如果房子里的居民感染了新型冠状病毒,那么房子两侧的房子也很有可能被诊断为冠状病毒。这将导致几乎所有房屋都极有可能受到新冠肺炎的影响。

听到这个消息,XYZ国家的总统决定处决(杀害(一些房子里的居民,以从那条街上拯救更多的人。

您将得到一个输入字符串,其中包含特定街道相邻房屋的居民人数。您的任务是找到可以避免感染新冠肺炎的最大居民人数。

输入格式:输入字符串包含一组由空格分隔的整数

限制:1<小巷里的房子<1000.

输出格式:打印可以避免感染新冠肺炎的最大居民人数。

样本输入:3 5 3 4 3 6

输出:15

我通过了测试用例0,但总体而言,我的答案仍然是错误的。

#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string input = "3 5 3 4 3 6", temp="";
int length = input.size(), i,j,scount=0,ncount=0,incl,excl=0,excl_new,temp2;
char ch;
for(i=0; i<length;i++)
{
ch = input[i];
if(ch == ' ')
{
++scount;
}
if(isdigit(ch))
{
++ncount;
}
}
if(ncount>1 && scount<=1000)
{
for(i=0; i<length;i++)
{
ch = input[i];
if (isdigit(ch))
{
temp += ch;
}
else
{
stringstream(temp)>>incl;
j = i;
break;
}
}
temp ="";
for(i=j; i<=length;i++)
{
ch = input[i];
if (isdigit(ch))
{
temp += ch;
}
else if(temp=="")
{
continue;
}
else
{
stringstream(temp)>>temp2;
temp ="";
if(incl>excl)
excl_new = incl;
else
excl_new = excl;
incl = excl + temp2;
excl = excl_new;
}
}
if(incl>excl)
cout<<incl;
else
cout<<excl;
return 0;
}
}

根据问题陈述中给出的输入,您可以简单地分别计算偶数和奇数房屋中所有居民的总和;然后,得到二者中的最大值。这会给你不相邻的房子里的居民人数。

例如:

3 5 3 4 3 6    // Residents in adjacent houses
3 _ 3 _ 3 _    // Sum: 9
_ 5 _ 4 _ 6    // Sum: 15
Maximum: 15    // Maximum of the two sums

如输入字符串将是由空间分隔的整数集的问题所示,一种方法可以是使用std::istringstream来提取整数。如果输入是通过STDIN,那么std::cin就足够了。剩下的将是计算偶数和奇数位置的所有整数的和;以及两个和的最大值。

这里有一个例子供您参考(直播(:

#include <iostream>
#include <algorithm>
#include <sstream>
auto calculateResidents( const std::string& input )
{
auto evenSum {0u};
auto oddSum  {0u};
std::istringstream iss{ input };
for ( auto i{0u}, n{0u}; iss >> n; ++i )
{
( i & 1 ) ? oddSum += n : evenSum += n;
}
return std::max( evenSum, oddSum );
}
int main()
{
const std::string input{ "3 5 3 4 9 6" };
std::cout << calculateResidents( input );
return 0;
}

输出:

15

这决不是解决你问题的现成办法!仅将此示例用作指导原则!您需要根据自己对C++语言设施的理解来制定自己的算法。你可能需要处理一些角落里的案子。祝你好运

最新更新