习题4.1 输出3个人的顺序
3个人比饭量大小,每人说了两句话。
A说: B比我吃得多,C和我吃得一样多。
B说: A比我吃得多,A也比C吃得多。
C说: 我比B吃得多,B比A吃得多。
事实上饭量越小的人讲对的话越多。请编程按饭量的大小输出3个人的顺序。
//************************************************
//* Source Name: ChapterFour_ExerciseOne.cpp
//* Founction : Output the order of 3 people
//* Author : Skyera
//* Create Time : 2025-7-18
//* Modify :
//* Modify Time:
//************************************************
#include <iostream>
#include <vector>
#include <algorithm>struct Person {std::string name;int statementCorrect;int appetite;
};// 检查一个排列是否符合条件
bool checkValue(const std::vector<Person>& people)
{std::vector<Person> sortedPeople = people;// 按饭量从小到大排序std::sort(sortedPeople.begin(),sortedPeople.end(),[](const Person& a, const Person& b){return a.appetite < b.appetite;});// 检查是否满足"饭量越小的人讲对的话越多"for(size_t i=0; i < sortedPeople.size()-1; i++){if(sortedPeople[i].statementCorrect <= sortedPeople[i+1].statementCorrect){return false;}}return true;
}int main()
{// 枚举所有可能的饭量排列(A, B, C的饭量分别为1, 2, 3的一个排列)std::vector<int> perm = {1, 2, 3};do{// 创建三个人物Person A = {"A", 0, perm[0]};Person B = {"B", 0, perm[1]};Person C = {"C", 0, perm[2]};// 计算每个人说对的话的数量// A说: B比我吃得多,C和我吃得一样多。if(B.appetite > A.appetite) A.statementCorrect++;if(C.appetite == A.appetite)A.statementCorrect++;// B说: A比我吃得多,A也比C吃得多。if(A.appetite > B.appetite)B.statementCorrect++;if(A.appetite > C.appetite)B.statementCorrect++;// C说: 我比B吃得多,B比A吃得多。 if(C.appetite > B.appetite)C.statementCorrect++;if(B.appetite > A.appetite)C.statementCorrect++;std::vector<Person> people = {A, B, C};// 检查是否符合条件if(checkValue(people)){// 按饭量从大到小排序并输出std::sort(people.begin(), people.end(), [](const Person& a, const Person& b){return a.appetite > b.appetite;});std::cout << "饭量从大到小的顺序是: "; for(const auto& p : people) {std::cout << p.name << " ";}std::cout << std::endl;return 0;}}while(std::next_permutation(perm.begin(), perm.end()));std::cout<<"没有符合条件的排列"<<std::endl;return 0;
}