华为2014届机试题之田忌赛马

71 篇文章 2 订阅
26 篇文章 0 订阅
package com.huawei.TianJiSaiMa;

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 广义田忌赛马:每匹马都有一个能力指数,齐威王先选马,田忌后选,马的能力相同,则齐威王胜。
 * 输入:马匹数量 \n 齐威王的马匹能力值 \n 田忌的马匹能力值(能力值之间都是以空格分开)
 * eg:输入:3 \n 1 2 3 \n 1 2 3 输出:2
 * @author patrick
 *
 */
public class TianJiSaiMa {
    public static void main(String args[]) {
        List<Integer> lTian = new ArrayList<Integer>();
        List<Integer> lQi = new ArrayList<Integer>();
        Scanner in = new Scanner(System.in);
        System.out.println("参加赛马的马匹数量:");
        int n = Integer.parseInt(in.nextLine().trim());
        // 先得到齐威王的田忌的能力值
        System.out.println("齐威王的马匹能力值:");
        String qi = in.nextLine().trim();
        // 然后得到田忌的田忌的能力值
        System.out.println("田忌的马匹能力值:");
        String tian = in.nextLine().trim();
        if (!tian.matches("[\\d+ ]*") || !qi.matches("[\\d+ ]*")) {
            System.err.println("input error !");
            return;
        }
        String[] tAblity = tian.split(" ");
        String[] qAblity = qi.split(" ");
        if (tAblity.length != n || qAblity.length != n) {
            System.err.println("the number of horses wrong !");
            return;
        }
        for (int i = 0; i < n; i++) {
            lTian.add(Integer.parseInt(tAblity[i]));
            lQi.add(Integer.parseInt(qAblity[i]));
        }
        Collections.sort(lTian);
        Collections.sort(lQi);

        int i = 0, j = 0, x = n - 1, y = n - 1, cnt = 0;
        boolean bLast = true;

        while (bLast) {
            // 是否是最后一匹马
            if (x == i)
                bLast = false;
            if (lTian.get(x) > lQi.get(y)) {// 如果田忌当前最好的马可以胜齐王最好的马,那么比一场
                x--;
                y--;
                cnt += 1;
            } else if (lTian.get(i) > lQi.get(j)) {// 如果田忌当前最差的马可以胜齐王最差的马,那么比一场
                i++;
                j++;
                cnt += 1;
            } else {// 否则,让田忌最差的马和齐王最好的好比一场
                i++;
                y--;
            }
        }
        System.out.println("田忌可以赢得赛马的场数为 " + cnt + " 场。");
        lTian.clear();
        lQi.clear();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值