[BOJ 4821,CPP] Page counting
BOJ 4821 "页数计算 "问题的 C++ 解决方案
问题链接
分类
实现, 字符串, 解析
包括
我最近加入了一家新公司,工作相当繁忙。作为一名新员工,刚进公司就感觉压力很大......不过,我一直在写下各种故事,相信迟早会讲出来的。
最近,我有一个学习 C 语言的好机会,每当学习 Python 或 Java 遇到时间墙时,我总是很失望,所以我想借此机会用 C++ 解决问题。
从我使用 C++ 的短暂经历来看,我有一种很好的感觉,那就是它的很多实现都相当繁琐,但速度却能弥补这一点。一旦我掌握了它的诀窍,是否就能利用它的速度优势......?我很期待。
说明。
向量:动态数组结构,类似于数组,但最大的优点是大小可以灵活改变,内存分配是自动的!
- npos:无位置,当位置无效时检查索引值。
stringstream: 将字符串视为流的设备,允许将其视为输入和输出,常用于解析
基本逻辑是创建一个可以覆盖整个页面限制范围的 bool 数组,然后检查所有输入的页面范围,最后输出计数值。
不过,值得注意的是,问题中给出的数值范围可能超出 int 值,因此需要设置一个变量来控制,而且如果给出的范围顺序相反,也有不检查的例外情况。
这在 Python 中相当容易实现,但当我尝试用 C++ 实现时,代码变得非常长...
解决方案代码
// 페이지 세기
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int total_page, seperator, start, end, result;
string temp, each_range;
vector<string> line_info;
vector<bool> print_info;
vector<int> result_vector;
while (true)
{
cin >> total_page;
if (!total_page)
break ;
else
{
print_info.assign(1001, false);
cin.ignore();
getline(cin, temp);
stringstream range_stream(temp);
while (getline(range_stream, each_range, ','))
{
if (each_range.find('-') == string::npos)
{
if (each_range.length() < 5 && stoi(each_range) <= 1000)
print_info[stoi(each_range)] = true;
}
else
{
seperator = each_range.find('-');
if (each_range.substr(0, seperator).length() < 5
&& stoi(each_range.substr(0, seperator)) <= 1000)
start = stoi(each_range.substr(0, seperator));
else
start = 1001;
if (each_range.substr(seperator + 1, each_range.size()).length() < 5
&& stoi(each_range.substr(seperator + 1, each_range.size())) <= 1000)
end = stoi(each_range.substr(seperator + 1, each_range.size()));
else
end = 1001;
if (start <= end)
{
for (int i = start; i <= end; i++)
{
if (i <= total_page)
print_info[i] = true;
}
}
}
}
result = 0;
for (int i = 1; i <= total_page; i++)
{
if (print_info[i])
result++;
}
result_vector.push_back(result);
}
}
for (int i = 0; i < (int) result_vector.size(); i++)
cout << result_vector[i] << endl;
return (0);
}
댓글 작성
게시글에 대한 의견을 남겨 주세요.