Codeforce C. Mere Array
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a1,a2,…,an where all ai are integers and greater than 0.
In one operation, you can choose two different indices i and j (1≤i,j≤n). If gcd(ai,aj) is equal to the minimum element of the whole array a, you can swap ai and aj. gcd(x,y) denotes the greatest common divisor (GCD) of integers x and y.
Now you’d like to make a non-decreasing using the operation any number of times (possibly zero). Determine if you can do this.
An array a is non-decreasing if and only if a1≤a2≤…≤an.
Input
The first line contains one integer t (1≤t≤104) — the number of test cases.
The first line of each test case contains one integer n (1≤n≤105) — the length of array a.
The second line of each test case contains n positive integers a1,a2,…an (1≤ai≤109) — the array itself.
It is guaranteed that the sum of n over all test cases doesn’t exceed 105.
Output
For each test case, output “YES” if it is possible to make the array a non-decreasing using the described operation, or “NO” if it is impossible to do so.
题目大意:如果a[i] 和 a[j] 的最大公约数是数组a 中的最小数,则可以交换a[i] 和 a[j],是否可以使数组a 成为非递减数组
题解:如果一个数是 minn 的倍数,则这个数可以和 minn 交换,我们可以吧minn 作为两个都是minn 倍数的数的桥梁,则这个数组中可以交换的数必是最小数的倍数。所以对原数组进行排序并比较,如果非最小数的倍数位置改变,则NO.
AC代码:
#include<bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i <= b; i ++)
using namespace std;
typedef long long ll;
int a[100005];
int b[100005];
int main()
{
int t = 1;
cin >> t;
while(t--){
int n;
cin >> n;
int minn = 1e9;
rep(i, 1, n){
cin >> a[i];
b[i] = a[i];
if(a[i] < minn){
minn = a[i];
}
}
bool flag = 1;
sort(b + 1, b + 1 + n);
rep(i, 1, n){
if(a[i] != b[i]){
if(b[i]%minn){
flag = 0;
break;
}
}
}
if(flag == 0) cout << "NO\n";
else cout << "YES\n";
}
}