牛客练习赛18-B 简单多边形

comes 2 U

题目描述

为了让所有选手都感到开心,Nowcoder练习赛总会包含一些非常基本的问题。 比如说:
按顺时针或逆时针方向给你一个简单的多边形的顶点坐标,请回答此多边形是顺时针还是逆时针。

输入描述:

输入包含N + 1行。
第一行包含一个整数N,表示简单多边形的顶点数。
在下面的N行中,第i行包含两个整数xi,yi,表示简单多边形中的第i个顶点的坐标。

输出描述:

如果简单多边形按顺时针顺序给出,则在一行中输出“clockwise”(不带引号)。 否则,打印”counterclockwise”(不带引号)。

示例1
输入

3
0 0
1 0
0 1

输出

counterclockwise

示例2
输入

3
0 0
0 1
1 0

输出

clockwise

备注:

3≤N≤30
-1000≤xi,yi≤1000
数据保证,这个简单多边形的面积不为零。

思路
  1. Green公式:https://blog.csdn.net/henuyh/article/details/80378818
  2. 叉积判断
    多边形可能是凹多边形,所以要统计叉积正负的数量。如果正数多逆时针,负数多顺时针。

AC

//Green公式
#include<bits/stdc++.h> 
#define N 100005
using namespace std;
struct ac {
    int x, y;
}a[N]; 
int main() {
//  freopen("in.txt", "r", stdin);
    int n;
    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n;i ++) {
            scanf("%d%d", &a[i].x, &a[i].y);
        }
        double d = 0;
        for (int i = 0; i < n - 1; i++) {
            d += -0.5 * (a[i].y + a[i + 1].y) * (a[i + 1].x - a[i].x); 
        }
        if (d < 0)  cout << "clockwise\n";
        else    cout << "counterclockwise\n";       
    }
    return 0;
}
//计算叉积
#include<bits/stdc++.h> 
#define ll long long
#define N 100005
using namespace std;
struct ac {
    int x, y;
}a[N]; 
//计算叉积 
int cross_product(ac a, ac b, ac c) {
    int x1 = b.x - a.x;
    int y1 = b.y - a.y;
    int x2 = c.x - b.x;
    int y2 = c.y - b.y;
    return x1 * y2 - x2 * y1;
}
int main() {
//  freopen("in.txt", "r", stdin);
    int n;
    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n;i ++) {
            scanf("%d%d", &a[i].x, &a[i].y);
        }
        //统计正负值数量 
        int integer = 0, negative = 0;
        for (int i = 0; i < n - 2; i++) {
            int t = cross_product(a[i], a[i + 1], a[i + 2]);
            if (t > 0)  integer++;
            if (t < 0)  negative++;
        }
        if (integer < negative) cout << "clockwise\n";
        else    cout << "counterclockwise\n";       
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/henuyh/article/details/80378981