#P3095. 高矮个子排队(100分)
-
1000ms
Tried: 257
Accepted: 57
Difficulty: 3
所属公司 :
华为od
高矮个子排队(100分)
循环
根据用例逻辑思路,循环每一个人的身高,需要调整使得 h1 >= h2 <= h3 >= h4 <= h5 ... 这种模式,遍历到第奇数个人的时候判断是不是小于他右边那个人如果是则交换两人位置,对于偶数如果是大于他右边的人身高则交换位置即可 当h1>=h2>h3时交换h2,h3不会出现不符合题意的情况
代码如下
cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define N 100005
int a[N];
int n = 1;
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s;
while (cin >> s) {
int res=0;
for(char c:s){
if(!isdigit(c)){
cout << "[]";
return 0;
}
res=res*10+c-'0';
}
a[n]=res;
n++;
}
n--;
// 3 5 4
for (int i = 1; i < n; i++) {
if (i & 1) { //目前是高
if (a[i] < a[i + 1]) {
swap(a[i], a[i + 1]);
}
} else { //目前是矮
if (a[i] > a[i + 1]) {
swap(a[i], a[i + 1]);
}
}
}
for(int i=1;i<=n;i++){
cout<<a[i]<<' ';
}
cout<<'\n';
return 0;
}
python
```python
def main():
a = []
s = input()
numbers = s.split()
for num in numbers:
if not num.isdigit():
print("[]")
return
res = int(num)
a.append(res)
n = len(a)
for i in range(0,n-1):
if i % 2 == 0:
if a[i] < a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
else:
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
print(' '.join(map(str, a)))
if __name__ == "__main__":
main()
java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Long> a = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String[] numbers = s.split(" ");
for (String num : numbers) {
if (!num.matches("\\d+")) {
System.out.print("[]");
return;
}
long res = Long.parseLong(num);
a.add(res);
}
int n = a.size();
for (int i = 0; i < n - 1; i++) {
if (i % 2 == 0) {
if (a.get(i) < a.get(i + 1)) {
long temp = a.get(i);
a.set(i, a.get(i + 1));
a.set(i + 1, temp);
}
} else {
if (a.get(i) > a.get(i + 1)) {
long temp = a.get(i);
a.set(i, a.get(i + 1));
a.set(i + 1, temp);
}
}
}
for (long height : a) {
System.out.print(height + " ");
}
System.out.println();
}
}
题目描述
现在有一队小朋友,他们高矮不同,我们以正整数数组表示这一队小朋友的身高,如数组{5,3,1,2,3}。
我们现在希望小朋友排队,以“高”“矮”“高”“矮”顺序排列,每一个“高”位置的小朋友要比相邻的位置高或者相等;每一个“矮”位置的小朋友要比相邻的位置矮或者相等;
要求小朋友们移动的距离和最小,第一个从“高”位开始排,输出最小移动距离即可。
例如,在示范小队{5,3,1,2,3}中,{5,1,3,2,3}是排序结果。
{5,2,3,1,3} 虽然也满足“高”“矮”“高”“矮”顺序排列,但小朋友们的移动距离大,所以不是最优结果。
移动距离的定义如下所示:
第二位小朋友移到第三位小朋友后面,移动距离为1,若移动到第四位小朋友后面,移动距离为2;
输入描述
排序前的小朋友,以英文空格的正整数:
4 3 5 7 8
注:小朋友<100个
输出描述
排序后的小朋友,以英文空格分割的正整数:4 3 7 5 8
备注:4(高)3(矮)7(高)5(矮)8(高), 输出结果为最小移动距离,只有5和7交换了位置,移动距离都是1。
样例1
输入
4 1 3 5 2
输出
4 1 5 2 3
样例2
输入
1 1 1 1 1
输出
1 1 1 1 1
说明
相邻位置可以相等
样例3
输入
xxx
输出
[]
说明
出现非法参数情况, 返回空数组。