题目描述:
下图中,每个方块代表一个像素,每个像素用其行号和列号表示,但可以发现,这种表示不是最简的,其实只需要存储 6 个蓝色的关键点即可,它们是线段的起点、拐点、终点,而剩下 4 个点是冗余的。现在,请根据输入的包含有冗余数据的多段线坐标列表,输出其最简化的结果。
输入描述:
2 8 3 7 3 6 3 5 4 4 5 3 6 2 7 3 8 4 7 5
1、所有数字以空格分隔,每两个数字一组,第一个数字是行号,第二个数字是列号;
2、行号和列号范围为[0,64),用例输入保证不会越界,考生不必检查;
3、输入数据至少包含两个坐标点。
输出描述:
2 8 3 7 3 5 6 2 8 4 7 5
压缩后的最简化坐标列表,和输入数据的格式相同。
特别注意:输出的坐标相对顺序不能变化。
示例1:
输入
2 8 3 7 3 6 3 5 4 4 5 3 6 2 7 3 8 4 7 5
输出
2 8 3 7 3 5 6 2 8 4 7 5
说明:
如上图所示,6 个蓝色像素的坐标依次是(2,8)、(3,7)、(3,5)、(6,2)、(8,4)、(7,5)。将他们按顺序出即可。
C++源码:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstdlib> // 添加此行以包含system函数
using namespace std;
int main() {
string line;
getline(cin, line);
istringstream iss(line);
vector<int> result;
vector<int> temp{ 0, 0 };
vector<int> temp_dif{ 0, 0 };
while (iss >> temp[0] >> temp[1]) {
result.push_back(temp[0]);
result.push_back(temp[1]);
for (string token; iss >> token;) {
if (token == "\n") break;
int x = stoi(token);
getline(iss >> ws, token, ' ');
int y = stoi(token);
int x_diff = x - temp[0];
int y_diff = y - temp[1];
temp = { x, y };
if (temp_dif[0] != 0 || temp_dif[1] != 0) {
if (x_diff * temp_dif[1] == y_diff * temp_dif[0]) {
result.pop_back();
result.pop_back();
}
}
temp_dif = { x_diff, y_diff };
result.push_back(x);
result.push_back(y);
}
for (size_t i = 0; i < result.size(); ++i) {
cout << result[i];
if (i < result.size() - 1) cout << " ";
}
cout << endl;
result.clear();
getline(cin, line);
iss.clear();
iss.str(line);
//if (cin.get() == '\n') {
// break;
//}
}
system("pause"); // 添加此行以运行后暂停
return 0;
}