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
數據保證,這個簡單多邊形的面積不為零。
思路
多邊形可能是凹多邊形,所以要統計叉積正負的數量。如果正數多逆時針,負數多順時針。
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; }總結
- 上一篇: 判断多边形边界曲线顺/逆时针
- 下一篇: 判断能被N整除的字符串