排序算法 差分 1895 B. Points and Minimum Distance

cpp 复制代码
#include<bits/stdc++.h>

using namespace std;

void solve()
{
	int n;
	cin>>n;
	
	vector<int> a(2*n);
	for(int i=0;i<2*n;i++)	cin>>a[i];
	sort(a.begin(),a.end());
	
	vector<int> b(n);
	for(int i=0;i<n;i++)
		b[i]=a[i];
	int ans=0;
	for(int i=0;i<n-1;i++)
	{
		ans+=b[i+1]-b[i];
		ans+=a[i+1+n]-a[i+n];
	}
	cout<<ans<<endl;	
	for(int i=0;i<n;i++)
		cout<<b[i]<<" "<<a[i+n]<<endl;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t;
	cin>>t;
	
	while(t--)
		solve();
	
	return 0;
}

独立写出来一道B题,还是非常开心的,该题主要是排序算法

排序+差分

要求最短的距离,所以最好就是按照从小到大的顺序排好,题目中定义了一种比较新的距离,两个横坐标的差,两个纵坐标的差,两者求和,差越小和就越小,所以把排序好的前面n个元素作为横坐标,后面n个元素作为纵坐标,做一个差分,然后求和就是答案,把前面n个元素存在一个数组里面方便输出,事实上不存也可以直接输出,我这个操作应该是多余了

cpp 复制代码
#include<bits/stdc++.h>

using namespace std;

void solve()
{
	int n;
	cin>>n;
	
	vector<int> a(2*n);
	for(int i=0;i<2*n;i++)	cin>>a[i];
	sort(a.begin(),a.end());
	
	int ans=0;
	for(int i=0;i<n-1;i++)
	{
		ans+=a[i+1]-a[i];
		ans+=a[i+1+n]-a[i+n];
	}
	cout<<ans<<endl;	
	for(int i=0;i<n;i++)
		cout<<a[i]<<" "<<a[i+n]<<endl;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t;
	cin>>t;
	
	while(t--)
		solve();
	
	return 0;
}

这样就简洁了许多

相关推荐
wusixuan13100429 分钟前
最大闭合子图学习笔记 / P2805 [NOI2009] 植物大战僵尸
笔记·学习·算法·最大闭合子图
孟大本事要学习1 小时前
算法第15天:继续二叉树|前序递归+回溯与前序递归的场景总结、最大二叉树、合并二叉树、二叉搜索树中的搜索、验证二叉搜索树
算法
GalaxyPokemon2 小时前
LeetCode - 76. 最小覆盖子串
运维·服务器·数据结构·算法·leetcode
嵌入式@秋刀鱼2 小时前
《 第三章-招式初成》 C++修炼生涯笔记(基础篇)程序流程结构
linux·开发语言·数据结构·c++·笔记·visual studio code
HaiQinyanAN2 小时前
【学习笔记】重载和重写的注意事项
c++·笔记·学习
手握风云-2 小时前
动态规划算法的欢乐密码(二):路径问题
算法·动态规划
西北大程序猿3 小时前
服务器代码知识点补充
服务器·开发语言·网络·c++·网络协议
Raven100863 小时前
L1G2-OpenCompass 评测书生大模型实践
算法
NAGNIP3 小时前
RAG信息检索-如何让模型找到‘对的知识’
算法
打不了嗝 ᥬ᭄4 小时前
进程控制
linux·运维·服务器·c++