题目 1153: C语言训练-谁家孩子跑最慢*

题目描述

张王李三家各有三个小孩。一天,三家的九个孩子在一起比赛短跑,规定不分年龄大小,跑第一得9分,跑第2得8分,依此类推。比赛结果各家的总分相同,且这些孩子没有同时到达终点的,也没有一家的两个或三个孩子获得相连的名次。已知获第一名的是李家的孩子,获得第二的是王家的孩子。问获得最后一名的是谁家的孩子?

输入格式

输出格式

输出最后一名的那家的姓的一个字母且以大写输出(若为张家,则输出Z)

样例输入

复制

样例输出

复制

W
#include <iostream>
#include <vector>
using namespace std;

// 检查是否满足条件
bool check(const vector<int>& scores) {
    int zhangScore = 0, wangScore = 0, liScore = 0;
    for (int i = 0; i < 9; ++i) {
        if (scores[i] == 1) zhangScore += 9 - i;
        else if (scores[i] == 2) wangScore += 9 - i;
        else if (scores[i] == 3) liScore += 9 - i;
    }
    // 检查每家的总分是否为15
    if (zhangScore != 15 || wangScore != 15 || liScore != 15) return false;

    // 检查是否有相连名次
    for (int i = 0; i < 8; ++i) {
        if (scores[i] == scores[i + 1]) return false;
    }

    // 检查已知条件
    if (scores[0] != 3 || scores[1] != 2) return false;

    return true;
}

// 打印结果
char getLastName(const vector<int>& scores) {
    return scores[8] == 1 ? 'Z' : (scores[8] == 2 ? 'W' : 'L');
}

// 回溯法尝试所有可能的分配方案
bool backtrack(vector<int>& scores, int index) {
    if (index == 9) {
        if (check(scores)) {
            cout << getLastName(scores) << endl;
            return true;
        }
        return false;
    }

    for (int i = 1; i <= 3; ++i) {
        scores[index] = i;
        if (backtrack(scores, index + 1)) {
            return true;
        }
    }
    return false;
}

int main() {
    vector<int> scores(9);
    if (!backtrack(scores, 0)) {
        cout << "No solution found." << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值