MT33. 最小排列
描述
输入描述
输出描述
输出一个 n 排列,表示能得到的最小的排列。示例1
输入:
3 3 2 1
输出:
1 2 3
示例2
输入:
4 2 1 4 3
输出:
1 2 4 3
C++ 解法, 执行用时: 14ms, 内存消耗: 2080KB, 提交时间: 2020-08-27
#include<bits/stdc++.h> using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int a[n]; for(int i=0; i<n; i++) cin >> a[i]; int i = 0, p = 0; for( ;i<n; i++) { if(a[i] != i+1) { p = i; break; } } if(i==n) { int t = a[n-1]; a[n-1] = a[n-2]; a[n-2] = t; } else { for(;i<n; i++) { if(a[i] == p+1) { int t = a[i]; a[i] = a[p]; a[p] = t; break; } } } for(int i=0; i<n; i++) { cout << a[i] << " "; } cout << endl; return 0; }
C 解法, 执行用时: 16ms, 内存消耗: 1712KB, 提交时间: 2021-09-17
#include<stdio.h> int main() { long n = 0; long i=1,j=0,tt=0,ttt=0,p=0,q=0; int flag = 0; while(scanf("%ld",&n) != EOF) { long *a = (long*)malloc(sizeof(long)*n); scanf("%ld",&a[0]); for(i=1;i<n;i++) { scanf("%ld",&a[i]); if(a[0] != 1) { if(a[i] == 1) { j = i; } } else { if(flag==0 && (a[i] != (a[i-1]+1))) { p=i; flag = 1; ttt = a[i]; tt = (a[i-1]+1); } else if(flag==1 && a[i] == tt) { q=i; } } } if(a[0] != 1) { a[j] = a[0]; a[0] = 1; } else if(a[0] == 1 && flag != 0) { a[p] = tt; a[q] = ttt; } else { long temp = a[n-1]; a[n-1] = a[n-2]; a[n-2] = temp; } for(long k=0;k<n;k++) { if(k == (n-1)) printf("%ld\n",a[k]); else printf("%ld ",a[k]); } } }