腾讯校招-2022.10.16-飞机
飞机 Problem Description
给定 n 个小飞机,初始时刻 0所有的小飞机都在数轴上,每个小飞机有两个属性,位置 x 和速度v,它们都以在数轴上以向右为正方向作匀速直线运动。 小Q可以进行任意次以下操作:选择两个飞机交换它们的初始位置,但不交换速度。小Q希望操作完毕后的飞机永远不会相撞,请你帮小Q输出交换后每个飞机的初始位置和初始速度。(需要按输入顺序的飞机编号输出)
input
第一行一个整数 n 。接下来 n 行,每行两个整数 x , v 。初始情况下保证没有两个小飞机的位置相同。1≤n≤105 ,−109≤x,v≤109
ouput
输出 n 行,每行输出两个整数,代表交换后每个飞机的位置和速度 合法解不止一个,输出任意合法解即可。
Sample Input 1
3
30 5
10 15
50 -1Sample Output 1
30 5
50 15
10 -1Sample Input 1
6
0 3
2 2
3 1
4 3
5 2
6 3Sample Output 1
4 3
3 2
0 1
6 3
2 2
5 3
题目类型、难度
- 类型:自定义排序
- 难度:简单题
总体思路:
- 只要按速度和位置分别从小到大排序即可,越左边的位置速度越小。
AC代码
#include <iostream>
#include <algorithm>
using namespace std;
struct plant{
int x;
int v;
int order;
};
bool com(struct plant &p1, struct plant &p2){
return (p1.v < p2.v);
}
bool com_order(struct plant &p1, struct plant &p2){
return (p1.order < p2.order);
}
int main(){
int n;
cin >> n;
struct plant *ps = new struct plant[n];
int *pos_x =new int[n];
for (int i = 0; i < n; i++){
cin >> ps[i].x >> ps[i].v;
ps[i].order = i;
pos_x[i] = ps[i].x;
}
sort(ps, ps+n, com);
sort(pos_x, pos_x+n);
for (int i = 0; i < n; i++){
ps[i].x = pos_x[i];
}
sort(ps,ps+n, com_order);
for (int i = 0; i < n; i++){
cout << ps[i].x << " " << ps[i].v << "\n";
}
return 0;
}
- 更多大厂真题可以看:2023实习、秋招互联网大厂技术岗算法真题-刷题(持续更新)