Circular Local MiniMax (数列特性问题+贪心)(CF 794,d2 C)

Circular Local MiniMax time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard output You are given n integers a1,a2,…,an. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors? In other words, check if there exists a rearrangement b1,b2,…,bn of the integers a1,a2,…,an such that for each i from 1 to n at least one of the following conditions holds: bi−1<bi>bi+1 bi−1>bi<bi+1 To make sense of the previous formulas for i=1 and i=n, one shall define b0=bn and bn+1=b1. Input The first line of the input contains a single integer t (1≤t≤3⋅104) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer n (3≤n≤105) — the number of integers. The second line of each test case contains n integers a1,a2,…,an (0≤ai≤109). The sum of n over all test cases doesn't exceed 2⋅105. Output For each test case, if it is not possible to arrange the numbers on the circle satisfying the conditions from the statement, output NO. You can output each letter in any case. Otherwise, output YES. In the second line, output n integers b1,b2,…,bn, which are a rearrangement of a1,a2,…,an and satisfy the conditions from the statement. If there are multiple valid ways to arrange the numbers, you can output any of them. Example inputCopy 4 3 1 1 2 4 1 9 8 4 4 2 0 2 2 6 1 1 1 11 111 1111 outputCopy NO YES 1 8 4 9 NO YES 1 11 1 111 1 1111 Note It can be shown that there are no valid arrangements for the first and the third test cases. In the second test case, the arrangement [1,8,4,9] works. In this arrangement, 1 and 4 are both smaller than their neighbors, and 8,9 are larger. In the fourth test case, the arrangement [1,11,1,111,1,1111] works. In this arrangement, the three elements equal to 1 are smaller than their neighbors, while all other elements are larger than their neighbors.
思路:
- 首先奇数数列,一定不会满足,(自己举一个栗子就行了)
- 偶数数列: 直接贪心 排序预处理,然后 后面n/2分别放在里面就行了

#include <bits/stdc++.h> using namespace std; #define ri register int #define M 100005 // 15:33 template <class G> void read(G &x) { x=0;int f=0;char ch=getchar(); while(ch<'0'||ch>'9'){f=ch=='-';ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} x=f?-x:x; return ; } int n; int t; int val[M]; int main(){ read(t); while(t--) { read(n); for(ri i=1;i<=n;i++) { read(val[i]); } if(n&1) { printf("NO\n"); continue; } sort(val+1,val+1+n); int flag=1; for(ri i=1;i<=n/2;i++) { int j=i+(n/2); int k=i+1;if(k>(n/2)) k=1; if(val[j]<=val[i]||val[j]<=val[k]) { flag=0;break; } } if(flag) { printf("YES\n"); for(ri i=1;i<=n/2;i++) { printf("%d %d ",val[i],val[i+n/2]); } printf("\n"); } else printf("NO\n"); } }