Problem
hihocoder.com/problemset/problem/1582
vjudge.net/problem/HihoCoder-1582
Reference
hihocoder 1582 : Territorial Dispute (计算几何)(2017 北京网络赛E)
Meaning
给出 n 个平面上的点,要把它们染成两种颜色 A 和 B,使得无法找到一条直线可以把所有的 A 和 B 完全的分开,求是否存在分配方案,如果有,输出任意一种分配。
Analysis
大概思路就是求个凸包,把凸包上的点间隔着 ABAB 地染色,凸包里面的点随便染。或者凸包一种色,凸包里的点另一种色。
如果所有点共线,且多于两个点,也是可以得。所有点共线时凸包里只有两个点(假的凸包?)。
如果只有 3 个点,且不共线,则是不行的。
综上,可以总结出一种策略:
先求凸包,如果凸包上的点 m < n(包含所有点共线的情况),则包上染 A,包里染 B;
否则,就是点全在凸包上(可能只有一个点),只要点数大于 3,就可以间隔着染色;
否则,就不在可行方案。
Code
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100;
struct pnt
{
int x, y, id;
pnt(int _x = 0, int _y = 0) :
x(_x), y(_y) {}
bool operator < (const pnt &rhs) const
{
return x != rhs.x ? x < rhs.x : y < rhs.y;
}
pnt operator - (const pnt &rhs) const
{
return pnt(x - rhs.x, y - rhs.y);
}
int operator ^ (const pnt &rhs) const
{
return x * rhs.y - rhs.x * y;
}
} p[N], ch[N<<1];
int Graham(int n)
{
sort(p, p + n);
int k = 0;
for(int i = 0; i < n; ++i)
{
while(k > 1 && ((ch[k-1] - ch[k-2]) ^ (p[i] - ch[k-1])) <= 0)
--k;
ch[k++] = p[i];
}
for(int i = n - 2, m = k; i >= 0; --i)
{
while(k > m && ((ch[k-1] - ch[k-2]) ^ (p[i] - ch[k-1])) <= 0)
--k;
ch[k++] = p[i];
}
// 注意 k = 1 的情况
return k > 1 ? k - 1 : k;
}
char ans[N+1];
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i)
{
scanf("%d%d", &p[i].x, &p[i].y);
p[i].id = i;
}
int m = Graham(n);
// 先全部染成 A
memset(ans, 'A', sizeof ans);
ans[n] = '\0';
if(m < n)
{
// 凸包上染 B
for(int i = 0; i < m; ++i)
ans[ch[i].id] = 'B';
printf("YES\n%s\n", ans);
}
else if(m > 3)
{
// 间隔着染 B(有两个就行)
ans[ch[0].id] = ans[ch[2].id] = 'B';
printf("YES\n%s\n", ans);
}
else
puts("NO");
}
return 0;
}