本文为 CCF 认证学习笔记,讲解题目线性分类器。欢迎在评论区与我交流😊
【传送门】
思路
简单模拟即可。
首先将所有点存在结构体数组中,用 vector 方便存储。对于每条直线,首先判断第一个点位置和类型的关系,从而确定所有点类型与直线的关系。如果有点与第一个确定出的关系不符,则判断为 No。
代码
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
struct Point {
ll x, y;
char type;
// 构造函数
Point(ll _x, ll _y, char _type): x(_x), y(_y), type(_type){}
};
int main() {
int n, m;
scanf("%d%d", &n, &m);
vector<Point> P;
for(int i = 0; i < n; ++i){
ll _x, _y;
char _type;
scanf("%lld%lld %c", &_x, &_y, &_type); // 注意有空格
P.push_back(Point(_x, _y, _type)); // 使用结构体的构造函数
}
while (m--) {
ll theta0, theta1, theta2;
scanf("%lld%lld%lld", &theta0, &theta1, &theta2);
// 确定点类型与直线的关系
int sign; // 0 表示 A 代入方程 >0;1 表示 A 代入方程 <0
if(P[0].type == 'A'){
if(theta0 + theta1 * P[0].x + theta2 * P[0].y > 0)
sign = 0;
else sign = 1;
}
else{
if(theta0 + theta1 * P[0].x + theta2 * P[0].y > 0)
sign = 1;
else sign = 0;
}
// 遍历所有点找出非法点
bool right = true;
for(int i = 1; i < n; ++i){
if(sign == 0){ // A > 0
if(theta0 + theta1 * P[i].x + theta2 * P[i].y > 0 && P[i].type == 'B'){
right = false;
break;
}
else if(theta0 + theta1 * P[i].x + theta2 * P[i].y < 0 && P[i].type == 'A'){
right = false;
break;
}
}
else{ // A < 0
if(theta0 + theta1 * P[i].x + theta2 * P[i].y > 0 && P[i].type == 'A'){
right = false;
break;
}
else if(theta0 + theta1 * P[i].x + theta2 * P[i].y < 0 && P[i].type == 'B'){
right = false;
break;
}
}
}
if(right) printf("Yes\n");
else printf("No\n");
}
return 0;
}
有帮助的话点个赞加关注吧 😃