Codeforces 1174B Ehab Is an Odd Person

题目链接:http://codeforces.com/problemset/problem/1174/B

题意:给定长度 n 的数组,任意俩个相加为奇数的数可以交换数组中的位置,让这个数组尽量从小到大。

思路:不难发现只要 2 个数奇偶性不同就可以交换 ,对于纯奇数或纯偶数数组,它们是没办法交换任何数,原样输出即可。不是纯奇偶的数组,可以把任意的数换至你想要的位置,所以将数组 sort 排序输出即可。

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 1e5 +5;
 4 int n;
 5 int a[maxn];
 6 int main()
 7 {
 8     scanf("%d",&n);
 9     bool flag = false;
10     for(int i = 0;i < n;i++)
11     {
12         scanf("%d",&a[i]);
13         if(i&&!flag){
14             if(a[i]%2 != a[i-1]%2)
15                 flag = true;
16         }
17     }
18     if(flag)
19     {
20         sort(a,a+n);
21         for(int i = 0;i < n;i++) printf("%d ",a[i]);
22     }
23     else for(int i = 0;i < n;i++) printf("%d ",a[i]);
24     return 0;
25 }

猜你喜欢

转载自www.cnblogs.com/Carered/p/10972832.html