http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=528&page=show_problem&problem=4088

思路:由欧拉公式可知面=边+2-点
我们可以暴力求出新增的点,去重后再对每个点检查是否在每条线段内部(非端点),从而增加边数。

/*0.146s*/

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const double eps = 1e-10;

struct Point
{
    double x, y;
    Point(double x = 0.0, double y = 0.0): x(x), y(y) {}
};
typedef Point Vector;

int dcmp(double x)
{
    if (x < -eps) return -1;
    return fabs(x) > eps;
}

Vector operator + (const Vector& A, const Vector& B) { return Vector(A.x + B.x, A.y + B.y); }
Vector operator - (const Point& A, const Point& B) { return Vector(A.x - B.x, A.y - B.y); }
Vector operator * (const Vector& A, double p) { return Vector(A.x * p, A.y * p); }

bool operator < (const Point& a, const Point& b)
{
    return a.x < b.x || (a.x == b.x && a.y < b.y);
}

bool operator == (const Point& a, const Point &b)
{
    return dcmp(a.x - b.x) == 0 && dcmp(a.y - b.y) == 0;
}

double Dot(const Vector& A, const Vector& B) { return A.x * B.x + A.y * B.y; }
double Cross(const Vector& A, const Vector& B) { return A.x * B.y - A.y * B.x; }

Point GetLineIntersection(const Point& P, const Vector& v, const Point& Q, const Vector& w)
{
    Vector u = P - Q;
    double t = Cross(w, u) / Cross(v, w);
    return P + v * t;
}

bool SegmentProperIntersection(const Point& a1, const Point& a2, const Point& b1, const Point& b2)
{
    double c1 = Cross(a2 - a1, b1 - a1), c2 = Cross(a2 - a1, b2 - a1),
           c3 = Cross(b2 - b1, a1 - b1), c4 = Cross(b2 - b1, a2 - b1);
    return dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0;
}

bool OnSegment(const Point& p, const Point& a1, const Point& a2)
{
    return dcmp(Cross(a1 - p, a2 - p)) == 0 && dcmp(Dot(a1 - p, a2 - p)) < 0;
}

const int maxn = 305;
Point P[maxn], V[maxn * maxn];

int main()
{
    int n, kase = 0;
    while (scanf("%d", &n), n)
    {
        for (int i = 0; i < n; i++) scanf("%lf%lf", &P[i].x, &P[i].y), V[i] = P[i];
        n--;
        int c = n, e = n;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                if (SegmentProperIntersection(P[i], P[i + 1], P[j], P[j + 1]))
                    V[c++] = GetLineIntersection(P[i], P[i + 1] - P[i], P[j], P[j + 1] - P[j]);
        sort(V, V + c);
        c = unique(V, V + c) - V;
        for (int i = 0; i < c; i++)
            for (int j = 0; j < n; j++)
                if (OnSegment(V[i], P[j], P[j + 1])) e++;
        printf("Case %d: There are %d pieces.\n", ++kase, e + 2 - c);
    }
    return 0;
}

Comments

comments powered by Disqus