代码1:正常思路+STL
/*线性分类器*/
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL; //此处是关键
struct point{
int xn, yn;
char c;
};
vector<point> a; //存储A类点
vector<point> b; //存储B类点
int main()
{
int n, m, cnta = 0, cntb = 0;
cin >> n >> m;
for(int i = 0; i < n; i ++)
{
int x, y;
char c;
point p;
cin >> x >> y >> c;
p.xn = x;
p.yn = y;
if(c == 'A'){
a.push_back(p);
}
if(c == 'B'){
b.push_back(p);
}
}
for(int i = 0; i < m; i ++)
{
int a0, a1, a2, t = 0;
LL cala, calb, cal; //此处要用long long类型,因为下面两个函数值相乘可能会超出int的范围
cin >> a0 >> a1 >> a2;
cala = a0 + a1*a[0].xn + a2*a[0].yn;
calb = a0 + a1*b[0].xn + a2*b[0].yn;
for(int j = 0; j < a.size(); j ++)
{
cal = a0 + (LL)a1*a[j].xn + (LL)a2*a[j].yn;
if(cal*cala > 0)
t ++;
else
break;
}
for(int k = 0; k < b.size(); k ++)
{
cal = a0 + (LL)a1*b[k].xn + (LL)a2*b[k].yn;
if(cal*calb > 0)
t ++;
else
break;
}
if(t == n && cala*calb < 0) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
代码2:简洁思路+结构体
/*线性分类器*/
#include <iostream>
using namespace std;
const int N = 1000 + 5;
struct point{
int xn, yn;
char v;
}a[N];
int main()
{
int n, m;
cin >> n >> m;
for(int i = 0; i < n; i ++)
{
cin >> a[i].xn >> a[i].yn >> a[i].v;
}
for(int i = 0; i < m; i ++)
{
int a0, a1, a2;
int A, B;
cin >> a0 >> a1 >> a2;
for(int j = 0; j < n; j ++)
{
if(a[0].v == 'A')//判定A、B在直线的哪一侧
{
if(a0 + a1*a[0].xn + a2*a[0].yn > 0){
A = 1, B = -1;//这样可以避免函数值超出int范围
}else{
A = -1, B = 1;
}
}
if(a[0].v == 'B')
{
if(a0 + a1*a[0].xn + a2*a[0].yn > 0){
B = 1, A = -1;
}else{
B = -1, A = 1;
}
}
}
int t = 1;
for(int j = 1; j < n; j ++)
{
if(a[j].v == 'A')
{
if((a0 + a1*a[j].xn + a2*a[j].yn)*A > 0){
t ++;
}else{
break;
}
}
if(a[j].v == 'B')
{
if((a0 + a1*a[j].xn + a2*a[j].yn)*B > 0){
t ++;
}else{
break;
}
}
}
if(t == n) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
-----------------------------------更新------------------------------------
#include <iostream>
using namespace std;
const int N = 1005;
typedef long long LL;//important!
struct point{
LL x, y;
char type;
}a[N];
int main()
{
LL n, m, A, B, a0, a1, a2, cal;
cin >> n >> m;
for(int i = 0; i < n; i ++)
{
cin >> a[i].x >> a[i].y >> a[i].type;
}
while(m --)
{
bool flag = false;
cin >> a0 >> a1 >> a2;
for(int i = 0; i < n; i ++) //定A的正负
{
cal = a0 + (LL)a1 * a[i].x +(LL) a2 * a[i].y;
if(a[i].type == 'A')
{
if(cal > 0) A = 1;
else A = -1;
break;
}
}
for(int i = 0; i < n; i ++)//定B的正负
{
cal = a0 + (LL)a1 * a[i].x +(LL) a2 * a[i].y;
if(a[i].type == 'B')
{
if(cal > 0) B = 1;
else B = -1;
break;
}
}
for(int i = 0; i < n; i ++)
{
cal = a0 + a1 * a[i].x + a2 * a[i].y;
if(a[i].type == 'A'){
if(cal * A > 0) continue;
else{
flag = true;
break;
}
}else{
if(cal * B > 0) continue;
else{
flag = true;
break;
}
}
}
if(!flag && (A * B < 0)) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}