【警示后人】关于scanf()和下标的错误
  • 板块P1878 舞蹈课
  • 楼主OhanaTyan
  • 当前回复1
  • 已保存回复1
  • 发布时间2024/5/21 18:12
  • 上次更新2024/5/21 20:35:12
查看原帖
【警示后人】关于scanf()和下标的错误
645279
OhanaTyan楼主2024/5/21 18:12

先贴出本人WA代码。这段代码只过了样例最后一个测试用例。

(可以直接划过,主要内容在后面)

#include <cstdio>
#include <cstdlib>
#include <queue>
#include <cassert>
#include <cstring>

struct B{
    int diff, l, r;
    bool operator>(const B& other)const{
        /*if (this->diff > other.diff)    return true;
        else if (this->diff<other.diff) return false;
        else {
            return this->l > other.l;
        }*/
        if (this->diff != other.diff){
            return this->diff > other.diff;
        }
        return this->l > other.l;
    }

    B(int d, int l, int r):diff(d), l(l), r(r){}
};
#ifdef DEBUG
constexpr int maxn = 100;
#else
constexpr int maxn = 2e5+10;
#endif
int a[maxn];
char g[maxn];
int is_visited[maxn];
int k;
int ls[maxn], rs[maxn];

int pre[maxn], next[maxn];

int main(){
    int n;
    scanf("%d", &n);
    scanf("%s", g);
    // assert(strlen(g) == n);
    for (int i=1; i<=n; i++){
        scanf("%d", a+i);
        pre[i] = i-1;
        next[i] = i+1;
    }

    pre[1] = 1;
    next[n] = n;
    std::priority_queue<B, std::vector<B>, std::greater<B>> q;

    for (int i=1; i<=n-1; i++){
        if (g[i]!=g[i+1]){
            q.push(B(abs(a[i]-a[i+1]), i, i+1));
        }
    }

    while (!q.empty()){
        B b = q.top();
        q.pop();
        int l=b.l, r=b.r;
        if (is_visited[l]==false && is_visited[r]==false){
            ls[k] = l;
            rs[k] = r;
            k++;
            is_visited[l]=is_visited[r] = 1;

            int ll = pre[l],
                rr = next[r];
            if (ll==0 || rr==0){
                continue;
            }            
            pre[rr] = ll;
            next[ll] = rr;
 
            if (g[ll] != g[rr]){
                q.push(B(abs(a[ll]-a[rr]), ll, rr));
            }
        }
    }

    printf("%d\n", k);
    for (int i=0; i<k; i++){
        printf("%d %d\n", ls[i], rs[i]);
    }
    return 0;
}

后来发现了错误原因:因为我这边数组是从 1 开始计数的,所以读入表示性别的串的时候,应该把

scanf("%s", g);

改成

scanf("%s", g+1);

这样,输入才会正确。

2024/5/21 18:12
加载中...