使用JAVA判斷凸多邊形的範例程式碼_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

以HDU2108為例,去AC吧。
//點逆序輸入
import java.util.Scanner;
//1s
public class HDU2108 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(true) {
      int x,y;
      int n = sc.nextInt();
      if(0==n) {
        break;
      }
      Point[] p = new Point[n];
      for(int i=0; i<n; i++) {
        p[i] = new Point();
      }
      for(int i=0; i<n; i++) {
        x = sc.nextInt();
        y = sc.nextInt();
        p[i] = new Point(x,y);
      }
      //凸多邊形
      boolean tag = true;
      int j,k,t;
      for(int i=0; i<n; i++) {
        //k,t直接對n求餘就行了
        j = i;
        k = i+1;
        t = i+2;
        //以三角形為例看看
        if(k==n) {
          k = 0;
        }
        if(t==n+1) {
          t = 1;
        }
        if(t==n) {
          t = 0;
        }
        //注意是後面減去前面的
        Point p1 = new Point(p[k].x - p[j].x,
            p[k].y - p[j].y);
        Point p2 = new Point(p[t].x - p[k].x,
            p[t].y - p[k].y);
        //叉積
        int ans = p1.x*p2.y - p1.y*p2.x;
        if(ans<0) {
          tag = false;
          break;
        }
      }
      if(tag) {
        System.out.println("convex");
      }else {
        System.out.println("concave");
      }
    }
  }
}
class Point {
  int x;
  int y;
  public Point() {
    this.x = 0;
    this.y = 0;
  }
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.