A. Cubes Sorting(思维)A. Cubes Sorting
原题链接: https://codeforces.com/contest/1420/problems
测试样例
input
3
5
5 3 2 1 4
6
2 2 2 2 2 2
2
2 1
output
YES
YES
NO
Note
In the first test case it is possible to sort all the cubes in 7 exchanges.
In the second test case the cubes are already sorted.
In the third test case we can make 0 exchanges, but the cubes are not sorted yet, so the answer is “NO”.
题意: 给你一个数组,你可以最多进行 n × ( n − 1 ) / 2 − 1 n\times(n-1)/2-1 n×(n−1)/2−1交换操作,交换规则为:相邻两元素交换。问你是否使得这个数组变为非递减数组。
解题思路: 这个交换操作次数就很灵性,为什么这么说呢?我们来看,我们要使得数组变为非递减数组,那么如果我这个数组就是一个完全递减数组,那么在这种情况下进行的操作数是不是最多的?(因为每次都要从最右端移到最左端) 我们来计算一下使得这种变为有序应该要进行多少操作次数,总共是 ( n − 1 ) + ( n − 2 ) + ⋅ ⋅ ⋅ + 1 (n-1)+(n-2)+···+1 (n−1)+(n−2)+⋅⋅⋅+1,那么根据等比数列求和公式直接可得要进行 n × ( n − 1 ) / 2 n\times(n-1)/2 n×(n−1)/2次操作,这和最大交换次数是不是仅差了一次,所以这种是必不可能的,那么对于其他不是完全递减的数组自然是可以完成的(至少会比完全递减数组操作数少1,自然满足)。故我们只要判断是不是完全递减的数组即可。这道题思维性很强,请仔细理解。
AC代码
/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h> //POJ不支持
#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
int t,n,a[maxn];
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
while(cin>>t){
while(t--){
cin>>n;
rep(i,0,n-1){
cin>>a[i];
}
bool flag=false;
rep(i,0,n-2){
if(a[i]<=a[i+1]){
flag=true;
break;
}
}
if(flag){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!