汽车-腾讯2023笔试(codefun2000)

题目链接
汽车-腾讯2023笔试(codefun2000)

题目内容

现在塔子哥有 n 个汽车,所有的汽车都在数轴上,每个汽车有1.位置 pos 2.速度 v ,它们都以在数轴上以向右为正方向作匀速直线运动。
塔子哥可以进行任意次以下操作:选择两个汽车交换它们的初始位置,但不交换速度。
塔子哥希望操作完毕后的汽车永远不会相撞,请你帮塔子哥输出交换后每个汽车的初始位置和初始速度。(需要按输入顺序的汽车编号输出)

输入描述

第一行一个整数 n 。
接下来 n 行,每行两个整数 pos , v 。
初始情况下保证没有两个汽车的位置相同。
1 ≤ n ≤ 1 0 5 , − 1 0 9 ≤ p o s , v ≤ 1 0 9 1≤n≤10^5,−10^9≤pos,v≤10^9 1n105,109pos,v109

输出描述

输出 n 行,每行输出两个整数,代表交换后每个汽车的位置和速度
合法解不止一个,输出任意合法解即可。

样例1

输入

3
11 17
15 -1
6 20

输出

11 17
6 -1
15 20

样例2

输入

5
1 6
4 -2
11 6
15 -9
10 2

输出

11 6
4 -2
15 6
1 -9
10 2

题解1

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;

int n;
struct Node{
	int idx; // 汽车编号
	int pos; // 汽车的位置
	int v; // 汽车的速度
}a[N], b[N], c[N];

bool cmp1(const Node& A, const Node& B){
	if(A.v != B.v) return A.v < B.v;
	return A.pos < B.pos;
}
bool cmp2(const Node& A, const Node& B){
	return A.pos < B.pos;
}

/*
题解: 将速度按升序排序,位置在左边的,速度小,位置在右边的,速度大,这样就可以保证所有的汽车不会相撞 
*/
int main(){
	scanf("%d", &n);
	for(int i = 1; i <= n; i++){
		scanf("%d%d", &a[i].pos, &a[i].v);
		a[i].idx = i;
	}	
	for(int i = 1; i <= n; i++){
		c[i].idx = b[i].idx = a[i].idx;
		c[i].pos = b[i].pos = a[i].pos;
		c[i].v = b[i].v = a[i].v;
	}
	sort(b + 1, b + n + 1, cmp1); // 将速度按升序排序 
	sort(c + 1, c + n + 1, cmp2); // 将位置按升序排序 
	
	for(int i = 1; i <= n; i++){
		a[b[i].idx].pos = c[i].pos; // a[b[i].idx]表示编号为b[i].idx的汽车的初始位置是c[i].pos 
	}
	for(int i = 1; i <= n; i++){
		printf("%d %d\n", a[i].pos, a[i].v);
	}
	return 0;
}
  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值