一开始写的以下C++代码,然后第一个点洛谷说我的输出是 0,但是我在本地(Windows)的 msvc,g++,clang++都复现不出来,在 Linux 测试了 g++ 也不能复现打印 0 的情况。
void solve() {
int64_t n;
cin >> n;
vector matrix(n, string());
size_t maxLen = 0;
cin.ignore();
for (auto &&line: matrix) {
getline(cin, line);
maxLen = max(maxLen, line.size());
}
for (auto &&line: matrix)
line.resize(maxLen, '*');
constexpr pair<int64_t, int64_t> dxy[]{{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
auto &&fill = [&](const auto &i, const auto &j) {
queue<pair<int64_t, int64_t>> q;
matrix[i][j] = '*';
for(q.emplace(i, j); not q.empty(); q.pop()) {
const auto &[x, y] = q.front();
for(const auto &[dx, dy] : dxy) {
auto px = x + dx, py = y + dy;
if(px < 0 or py < 0 or px >= n or static_cast<size_t>(py) >= maxLen or
matrix[px][py] == '*' or matrix[px][py] == ' ')
continue;
matrix[px][py] = '*';
q.emplace(px, py);
}
}
};
int64_t answer = 0;
for(auto &&i : views::iota(0, n))
for(auto &&j : views::iota(0ull, maxLen)) {
if(matrix[i][j] == '*' or matrix[i][j] == ' ')
continue;
answer++;
fill(i, j);
}
println("{}", answer);
}
你猜猜怎么着,把 cin.ignore() 改成下面这个,就能过解决第一个点不打印答案,而是打印 0 的问题,但是其他点仍然会 wa
for(char c = cin.get(); c == '\n';)
c = cin.get();
如果上面 cin.ignore() 中循环的代码,将输入进来的字符串,去掉'\r'和'\n',然后再跑算法,你就可以 AC这道题目。
根据个人猜测,这题的数据,是一个Windows(CRLF)换行符(\r\n)的数据(下载下来也是确实如此),但是评测环境却是Linux,导致了行尾处理的问题。
猜测的依据如下
这道题通过
rust实现的以下函数是不存在这个问题的
pub fn next_line(&mut self) -> String {
let mut str = String::new();
let _ = self.stream.read_line(&mut str);
return str.trim_end().to_string();
}
代码中用 .trim_end() 删除了末尾的 \r\n