Codeforces Round 1054 B. Unconventional Pairs(2149)
https://codeforces.com/contest/2149/problem/B
题意:
解题思路:
通过最后提示:可以发现,是偶数个元素,并且成对出现是排序过,然后求2个数之差,然后取最大的差值。
根据题意,是求,成对出现的数据之差,其差值,最大的是?
最小可能的,最大差值,在元素的对对中,根据NOTE就可以推理出来。
参考和别人的代码,消化理解完成。
/*
For a pair(x,y),its difference is defined as |x-y|.
Pet wants to form unconventional pairs such that the maximum difference amongall pairs is minimized.Detemine the minimun possible value of this maximum difference. Example
Input
5
2
1 2
4
10 1 2 9
6
3 8 9 3 3 2
8
5 5 5 5 5 5 5 5
4
-5 -1 2 6
Output
1
1
1
0
4Note
In the first test case, the array is: [1,2].
The only possible (and therefore optimal) pair is (1,2),
its difference is |1-2|=1,the answer is 1.In the second test case, the array is: [10,1,2,9].
We can choose pairs — (1,2) and (9,10): both differences are equal to 1,
therefore, the maximum difference is 1.In the third test case, the array is: [3,8,9,3,3,2].
We can choose pairs: (2,3), (3,3), (8,9). The differences are: 1,0,1
-the largest is 1.
*/#include <iostream>
using namespace std;//no used,for time to exceed!
void sort_bubble_by_asc(int *list,int len)
{ for (int i = 0; i < len - 1; i++){for (int j = 0; j < len - 1 - i; j++){if (list[j] > list[j + 1]){swap(list[j], list[j + 1]);}}}
}//Quick Query
int GetPositionBYQueckSort(int *list, int front, int back){int midPos = 0;int left = front;int right = back;while (left < right){//from right to startwhile (left < right && list[left] < list[right]){right--;}//to swapif (left < right){swap(list[left], list[right]);left++;}//right partwhile (left < right && list[left] < list[right]){left++;}if (left < right){swap(list[left], list[right]);right--;}}midPos = left;return midPos;
}
void sort_by_quick_exercise01(int *list, int front, int back)
{if (front < back){int mid = GetPositionBYQueckSort(list, front, back);sort_by_quick_exercise01(list, front, mid - 1); //front partsort_by_quick_exercise01(list, mid + 1, back); //back part}
}int get_max_value(int a, int b)
{if (a > b){return a;}else{return b;}
}int main()
{int t=0;int v1=0;int n=0;cin >> t;while (t--){ cin >> n;int *list = new int[n];for (int i = 0; i < n;i++){cin >> list[i];}//asc or des , all ok!//sort_bubble_by_asc(list, n); //this is time to exceed!!!sort_by_quick_exercise01(list,0,n-1);int rs = 0;int different = 0;// pair ,so i=i+2for (int i = 0; i < n; i += 2){different = list[i + 1] - list[i];rs = get_max_value(rs, different);}cout << rs <<endl;delete[] list;}return 0;
}
说明:不能用冒泡排序,当测试数据2万条的时候,就会超时,根据之前排序方法,只有快速排序
循环次数最少。
完成。