奇偶数分离

来源:互联网 发布:商城商品详情页面源码 编辑:程序博客网 时间:2024/05/17 23:11

描述
有一个整型偶数n(2<= n <=10000),你要做的是:先把1到n中的所有奇数从小到大输出,再把所有的偶数从小到大输出。
输入
第一行有一个整数i(2<=i<30)表示有 i 组测试数据;
每组有一个整型偶数n。
输出
第一行输出所有的奇数
第二行输出所有的偶数
样例输入
2
10
14
样例输出
1 3 5 7 9
2 4 6 8 10

1 3 5 7 9 11 13
2 4 6 8 10 12 14

算法思路:首先把算法想的有点复杂,以为输出只能按照格式输出,没想到可以分开输出,加大了空间的使用和时间的使用,将自己写的代码作为第一个例子展现出来,第二个例子是修改过后的代码,明显比较简单。运行没有错误。

#include <bits/stdc++.h>#include <iostream>#include <list>using namespace std;list<int> ou[10000];list<int> ji[10000];int main(){    int n;    cin >> n;    int num = 0;    for(int i = 0; i < n; i++)    {        cin >> num;        for(int j = 1; j <= num ; j++)        {            if(j % 2) ji[i].push_back(j);            else ou[i].push_back(j);        }       }    list<int> :: iterator it;    for(int i = 0; i < n; i++)    {        it = ji[i].begin();         while(it != ji[i].end())         {           cout << *it ;            it++;           if(it != ji[i].end()) cout << " ";         }        cout << endl;        it = ou[i].begin();         while(it != ou[i].end())         {              cout << *it;             it++;            if(it != ou[i].end()) cout << " ";         }         cout << endl;    }}

代码优化:

#include<stdio.h>int main(){    int n;    scanf("%d",&n);    int a;    while(n--)    {        scanf("%d",&a);        for(int i=1;i<=a;i+=2)        printf("%d ",i);        puts("");        for(int i=2;i<=a;i+=2)        printf("%d ",i);        puts("");    }}
0 0