返回题目问答
讨论 / 题目问答/ 帖子详情

为何逻辑相似,只是换用了数据输入方式,就能AC?

下面这是我让AI写的代码,后面接着我的代码,看着除了输入方式不一样之外,好像就没什么差别了,想不明白为什么我自己的代码AC不了,AI的却可以。。。。求大佬解答,感谢
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct Student {
    string name;
    int id;
    string className;
};

// 比较函数
bool compare(const Student& lhs, const Student& rhs) {
    if (lhs.className != rhs.className) {
        return lhs.className < rhs.className;
    }
    return lhs.id < rhs.id;
}

int main() {
    // 优化 I/O 速度
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    // 尝试处理多组输入,防止 WA
    while (cin >> n) { 
        vector<Student> students(n);
        for (int i = 0; i < n; ++i) {
            cin >> students[i].name >> students[i].id >> students[i].className;
        }

        sort(students.begin(), students.end(), compare);

        for (const auto& s : students) {
            cout << s.name << " " << s.id << " " << s.className << endl;
        }
    }
    return 0;
}


#include <cstdio>
#include "string"
#include "vector"
#include "algorithm"
using namespace std;
struct Student{
    string name;
    int id;
    string className;
    Student(char *_name, int _id, char *_className){
        name = _name;
        id = _id;
        className = _className;
    }
};

bool compare(Student lhs, Student rhs){
    if(lhs.className < rhs.className)   return true;
    else if(lhs.className == rhs.className && lhs.id < rhs.id)  return true;
    else return false;

}

int main() {
    vector<Student> students;

    int n, id;
    char buffer_name[50], buffer_className[50];
    while (scanf("%d", &n) != EOF){
        students.clear();
        while (n --){
            scanf("%s %d %s", buffer_name, &id, buffer_className);
            students.emplace_back(buffer_name, id, buffer_className);
        }
        sort(students.begin(), students.end(), compare);
        for(auto each: students){
            printf("%s %d %s\n", each.name.c_str(), each.id, each.className.c_str());
        }
    }

    return 0;
}
1 回复 0 转发 0 喜欢 13 阅读
回复 (1)
默认 最新
露米 2026/3/25
看到你贴出的代码啦,这种“逻辑看起来一样但结果不同”的情况确实挺让人困惑的。不过别担心,你写的代码结构其实已经很清晰了,逻辑上也是对的。

我注意到一个小细节,在你的代码里使用了 char buffer_name[50]。在算法竞赛中,如果题目给出的字符串长度超过了 49 个字符,这种写法可能会导致缓冲区溢出,从而引起程序运行异常。而 AI 写的代码直接使用了 std::string 配合 cin 读入,它会自动处理字符串的长度,这可能就是它能 AC 的一个小秘密。

另外,在 compare 函数里,建议可以参考 AI 的写法,使用 const Student& lhs 这种引用传递。这样在排序比较时,就不需要每次都把整个结构体复制一遍,运行起来会更轻松一些。

你可以试着把 buffer 数组改大一点,或者也尝试直接用 std::string 读入看看能不能通过?如果调整后还有其他报错,我们可以再一起分析 🙂
另外,在最后的输出循环里,你使用了 for(auto each: students),这会在每一轮循环时都对 Student 对象进行一次拷贝。虽然这通常不会直接导致逻辑错误,但在处理大数据量时,改用 const auto& each 这种引用方式会让程序运行得更轻快。

还有个非常细微的地方,头文件建议使用尖括号(如 <string><vector>)而不是双引号,这样更符合标准库的使用规范,也能避免在某些环境下出现奇奇怪怪的编译
0