Oiclass Q&A P1106

题目:

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "iostream"
#include "cstring"

using namespace std;
int n, cnt, t;
int main(){
cin >> n;
int a[n + 1];
memset(a, 0, sizeof a);
for (int i=1; i <= n; i++){
cin >> a[i];
}
for (int i=1; i <= n; i++){
for (int j=1; j <= n; j++){
if (a[j] > a[j+1]){
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
cnt += 1;
} else{
continue;
}
}
}
// for (int i=1; i <= n; i++){
// cout << a[i] << " ";
// }
cout << cnt;
}

超神奇的三次运行结果:

imageimage

经过大佬的提醒,事实问题在于数组没有设全局,修改思路如下:

把数组改成全局,并在交换的时候判断 a[j]a[j + 1]是否不为0,从而解决无效交换的问题,最终,历经千辛万苦,这道题还是AC了。实现的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "iostream"
#include "cstring"

using namespace std;
int a[10001];
int n, cnt, t;
int main(){
cin >> n;
for (int i=1; i <= n; i++){
cin >> a[i];
}
for (int i=1; i <= n; i++){
for (int j=1; j <= n; j++){
if (a[j] > a[j+1] && a[j] != 0 && a[j + 1] != 0){
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
cnt += 1;
} else{
continue;
}
}
}
// for (int i=1; i <= n; i++){
// cout << a[i] << " ";
// }
cout << cnt;
}

Oiclass Q&A P1106
https://lixuannan.github.io/posts/17897
作者
CodingCow Lee
发布于
2022年8月11日
许可协议