首页 > 后端开发 > C++ > 正文

安排前N个自然数,使得相邻元素的绝对差大于1

PHPz
发布: 2023-09-07 22:01:02
转载
1097人浏览过

安排前n个自然数,使得相邻元素的绝对差大于1

我们有前 N 个自然数。我们的任务是获得它们的一种排列,其中每两个连续元素之间的绝对差 > 1。如果不存在这样的排列,则返回 -1。

方法很简单。我们将使用贪心方法。我们将所有奇数按升序或降序排列,然后将所有偶数按降序或升序排列

MagicArena
MagicArena

字节跳动推出的视觉大模型对战平台

MagicArena 163
查看详情 MagicArena

算法

arrangeN(n)

Begin
   if N is 1, then return 1
   if N is 2 or 3, then return -1 as no such permutation is not present
   even_max and odd_max is set as max even and odd number less or equal to n
   arrange all odd numbers in descending order
   arrange all even numbers in descending order
End
登录后复制

Example

的中文翻译为:

示例

#include <iostream>
using namespace std;
void arrangeN(int N) {
   if (N == 1) { //if N is 1, only that will be placed
      cout << "1";
      return;
   }
   if (N == 2 || N == 3) { //for N = 2 and 3, no such permutation is available
      cout << "-1";
      return;
   }
   int even_max = -1, odd_max = -1;
   //find max even and odd which are less than or equal to N
   if (N % 2 == 0) {
      even_max = N;
      odd_max = N - 1;
   } else {
      odd_max = N;
      even_max = N - 1;
   }
   while (odd_max >= 1) { //print all odd numbers in decreasing order
      cout << odd_max << " ";
      odd_max -= 2;
   }
   while (even_max >= 2) { //print all even numbers in decreasing order
      cout << even_max << " ";
      even_max -= 2;
   }
}
int main() {
   int N = 8;
   arrangeN(N);
}
登录后复制

输出

7 5 3 1 8 6 4 2
登录后复制

以上就是安排前N个自然数,使得相邻元素的绝对差大于1的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号