A - Sorted Adjacent Differences
题意:给定数组,对其排序,使其满足|a1−a2|≤|a2−a3|≤…≤|an−1−an|.
解题思路:先对数组进行排序,由最大值与最小值之差最大,次大值与次小值之差第二大,依次类推,将数组从中间开始输出.
ac代码:
#include<iostream> #include<map> #include<cmath> #include<algorithm> using namespace std; int main(){ int t,n,i,j,a[100005]; cin>>t; while(t--){ cin>>n; for(i=0;i<n;i++){ cin>>a[i]; } sort(a,a+n); if(n%2==0){ cout<<a[n/2-1]<<" "<<a[n/2]; for(i=n/2-2,j=n/2+1;i>=0;i--,j++){ cout<<" "<<a[i]<<" "<<a[j]; } cout<<endl; } else{ cout<<a[n/2]; for(i=n/2-1,j=n/2+1;i>=0;i--,j++){ cout<<" "<<a[i]<<" "<<a[j]; } cout<<endl; } } return 0; }