CSP认证线性分类器

216 阅读1分钟

题目描述

page02.png

page03.png

page04.png

题目思路

同类型的坐标点应该在同一边,不同类型的坐标点应该在另外一边。 判断在一条直线上边还是下边的方法只是代入x and y.

题目解答



import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // 接收两个参数
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        // 接收坐标
        int[][] coordinate = new int[n][2];
        char[] type = new char[n];
        for (int i = 0; i < n; i++) {
            coordinate[i][0] = scanner.nextInt();
            coordinate[i][1] = scanner.nextInt();
            type[i] = scanner.next().charAt(0);
        }
        // 接收方程参数
        int[][] theta = new int[m][3];
        for (int i = 0; i < m; i++) {
            theta[i][0] = scanner.nextInt();
            theta[i][1] = scanner.nextInt();
            theta[i][2] = scanner.nextInt();
        }
        // 核心方法,判断是否分割

        // 得到第一个坐标的类型
        char firstType = type[0];
        // 定义结果数组
        boolean[] res = new boolean[m];
        for (int i = 0; i < theta.length; i++) {
            res[i] = true;
            // 判断第一个坐标代入方程是在下方还在上方
            boolean isUp = judgeIsUp(theta[i], coordinate[0]);
            // 从第二个坐标开始遍历,同类型的必须在同一边,不同类型的必须在另一边
            for (int j = 1; j < coordinate.length; j++) {
                // 如果类型相同,出现不同边的情况则false
                if (firstType == type[j]){
                    if (isUp != judgeIsUp(theta[i], coordinate[j])){
                        res[i] = false;
                        break;
                    }
                }else {
                    // 如果类型不同,则都要在另一边
                    if (isUp == judgeIsUp(theta[i], coordinate[j])){
                        res[i] = false;
                        break;
                    }
                }

            }

        }
        // 输出结果
        for (int i = 0; i < res.length; i++) {
            if (res[i]){
                System.out.println("Yes");
            }else {
                System.out.println("No");
            }
        }
    }

    private static boolean judgeIsUp(int[] theta, int[] corrdinate) {
        if ((theta[0] + (theta[1] * corrdinate[0]) + (theta[2] * corrdinate[1])) < 0){
            return false;
        }
        return true;
    }

}