社区讨论
【警示后人】关于scanf()和下标的错误
P1878舞蹈课参与者 1已保存回复 1
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 1 条
- 当前快照
- 1 份
- 快照标识符
- @lwg8lufu
- 此快照首次捕获于
- 2024/05/21 18:13 2 年前
- 此快照最后确认于
- 2024/05/21 20:35 2 年前
先贴出本人WA代码。这段代码只过了样例最后一个测试用例。
(可以直接划过,主要内容在后面)
CPP#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;
}
后来发现了错误原因:因为我这边数组是从
CPP1 开始计数的,所以读入表示性别的串的时候,应该把scanf("%s", g);
改成
CPPscanf("%s", g+1);
这样,输入才会正确。
回复
共 1 条回复,欢迎继续交流。
正在加载回复...