网易笔试题:比较重量

题目描述:

小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石g1和g2。现在请你根据之前比较的信息判断这两颗钻石的哪颗更重。
给定两颗钻石的编号g1,g2,编号从1开始,同时给定关系数组vector,其中元素为一些二元组,第一个元素为一次比较中较重的钻石的编号,第二个元素为较轻的钻石的编号。最后给定之前的比较次数n。请返回这两颗钻石的关系,若g1更重返回1,g2更重返回-1,无法判断返回0。输入数据保证合法,不会有矛盾情况出现。

测试样例:

2,3,[[1,2],[2,4],[1,3],[4,3]],4

返回: 1

思路:相当于是求有向图中的两个节点的可达性。分为两步,先构造有向图,再求可达性。

import java.util.Scanner;

public class WangyiTest4 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int g1 = scanner.nextInt();
        int g2 = scanner.nextInt();
        int n = scanner.nextInt();
        int[][] records = new int[n][n];
        for (int i = 0; i < n; i++) {
            records[i][0] = scanner.nextInt();
            records[i][1] = scanner.nextInt();
        }
        System.out.println(cmp(g1, g2, records, n));
    }

    public static int cmp(int g1, int g2, int[][] records, int n) {
        // 统计有向联通图的最大节点标号
        int maxIndex = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            maxIndex = records[i][0] > maxIndex ? records[i][0] : maxIndex;
            maxIndex = records[i][1] > maxIndex ? records[i][1] : maxIndex;
        }
        // 构造有向图
        int[][] map = new int[maxIndex + 1][maxIndex + 1];
        for (int i = 1; i <= maxIndex; i++) {
            for (int j = 1; j <= maxIndex; j++) {
                if (i == j) {
                    map[i][j] = 1; // 1 表示联通
                } else {
                    map[i][j] = 0;
                }
            }
        }
        for (int i = 0; i < n; i++) {
            map[records[i][0]][records[i][1]] = 1;
        }
        //间接可达的情况
        for (int k = 1; k <= maxIndex; k++) {
            for (int i = 1; i <= maxIndex; i++) {
                for (int j = 1; j <= maxIndex; j++) {
                    if (map[i][k] == 1 && map[k][j] == 1) {
                        map[i][j] = 1;
                    }
                }
            }
        }
        if (map[g1][g2] == 1) {
            return 1;
        } else if (map[g2][g1] == 1) {
            return -1;
        } else {
            return 0;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值