0分

B4066 [GESP202412 三级] 数字替换

jr001 @ 2024-12-24 16:32:41

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
ll n,d,a[1000001],b[1000001];
int main () {
    cin >> n>> d; 
    for(int i = 0; i<n; i++){
        cin >> a[i];
        a[i]=b[i];
    }
    sort(b, b+n);
    int x=b[0],m=b[n-1];
    for(int i = 0; i<n;i++){
        if(a[i]>d){
            a[i]=m;
        }else if(a[i]<d){
            a[i]=x;
        }
        cout << a[i]<<" ";
    }
    return 0;
}

by JmBecca @ 2024-12-24 16:38:03

@jr001

你的输入就有问题了:

在输入之前你建了两个数组a和b,而且你输入的变量是存在a数组里面的,那你下一行代码:

a[i]=b[i];

就应该是把b里面的每个元素替换到a里面,所以你相当于把数组a又换回到之前的状态了。就是说读了跟没读一样哈。反过来就AC了。求关哈,嘻嘻


by GarfieldSHIT @ 2024-12-25 12:53:51

@jr001

给你讲一下当时我一个小佬(因为我拿过csp-j二等奖)去考GSEP202412三级时的代码......

我先讲一下思路:

你不需要两个数组,内存太大,你想想,他要改的,是小于 d 的要改成数组中最小的那个数,大于 d 的要改成数组中最大的那个数,那你可不可以将每一个数字去进行判断(当然要在输入了之后)你可以逐一去判断每个数,输出答案,时间复杂度为 O(2n)

代码是:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll d, a[1000001], maxx = -0x3f3f3f3f3f3f3f3f, minn = 0x3f3f3f3f3f3f3f3f;
int n;
signed main() {
    cin >> n >> d;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        maxx = max(a[i], maxx);
        minn = min(a[i], minn);
    }
    for (int i = 0; i < n; i++) {
        if (a[i] < d) cout << minn << ' ';
        else if (a[i] > d) cout << maxx << ' ';
        else cout << a[i] << ' ';
    }
    return 0;
}

如果看不惯,还有下一种:

你可以枚举一个 k ,在 k 上面去判断,代码如下:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll d, a[1000001], maxx = -0x3f3f3f3f3f3f3f3f, minn = 0x3f3f3f3f3f3f3f3f;
int n;
int k[1000001];
signed main() {
    cin >> n >> d;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        maxx = max(a[i], maxx);
        minn = min(a[i], minn);
        if (a[i] < d) k[i] = 1;
        else if (a[i] > d) k[i] = 2;
    }
    for (int i = 0; i < n; i++) {
        if (k[i] == 1) cout << minn << ' ';
        else if (k[i] == 2) cout << maxx << ' ';
        else cout << a[i] << ' ';
    }
    return 0;
}

注意一下,如果没有学过 signed 是什么意思的话,建议把第二行删掉,把 ll 部分改回 long~long ,把 signed 改回 int


|