21点游戏
题目描述
问题描述:给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利
输入:
4个1-10的数字。[数字允许重复,但每个数字仅允许使用一次,测试用例保证无异常数字]
输出:
true or false
输入描述:
输入4个int整数
输出描述:
返回能否得到24点,能输出true,不能输出false
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void check24(const vector<int> &nums, int index, double result, bool &isSuccess)
{
if (index == 4) //递归结束条件
{
if (abs(result - 24) < 1e-6)
isSuccess = true;
return;
}
for (int i = 0; i < 4; i++)
{
if (i == 0)
check24(nums, index + 1, result + nums[index], isSuccess);
else if (i == 1)
check24(nums, index + 1, result - nums[index], isSuccess);
else if(i==2)
check24(nums, index + 1, result * nums[index], isSuccess);
else
check24(nums, index + 1, result / nums[index], isSuccess);
if (isSuccess)
return;
}
}
int main()
{
vector<int>nums(4);
while (cin >> nums[0] >> nums[1] >> nums[2] >> nums[3])
{
sort(nums.begin(), nums.end());
bool isSuccess = false;
do {
check24(nums, 0, 0, isSuccess);
if (isSuccess)
break;
} while (next_permutation(nums.begin(), nums.end()));
if (isSuccess)
cout << "true" << endl;
else
cout << "false" << endl;
}
return 0;
}
成绩排序
题目描述
查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
例示:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
Tom 70
jack 70
peter 96
输入描述:
输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开
输出描述:
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct student{
string name;
int score;
};
bool cmp0(const student &a, const student &b){
// 从高到低排序
return a.score > b.score;
}
bool cmp1(const student &a, const student &b){
// 从低到高排序
return a.score < b.score;
}
int main(){
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int N, type;
while(cin >> N >> type){
vector<student> stud(N);
for(int i = 0; i < N; i ++){
cin >> stud[i].name >> stud[i].score;
}
if(type == 0)
stable_sort(stud.begin(), stud.end(), cmp0);
else
stable_sort(stud.begin(), stud.end(), cmp1);
for(int i = 0; i < N; i ++){
cout << stud[i].name << " " << stud[i].score << endl;
}
}
return 0;
}
字符串通配符
题目描述
问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
要求:
实现如下2个通配符:
*:匹配0个或以上的字符(字符由英文字母和数字0-9组成,不区分大小写。下同)
?:匹配1个字符
输入:
通配符表达式;
一组字符串。
输出:
返回匹配的结果,正确输出true,错误输出false
输入描述:
先输入一个带有通配符的字符串,再输入一个需要匹配的字符串
输出描述:
返回匹配的结果,正确输出true,错误输出false
#include<iostream>
using namespace std;
bool match(char *str1, char *str2)
{
if(*str1 == '\0' && *str2 == '\0')
return true;
else if(*str1 == '\0' || *str2 == '\0')
return false;
if(*str1 == '?')
return match(str1+1, str2+1);
else if(*str1 == '*')
return match(str1+1, str2) || match(str1+1, str2+1) || match(str1, str2+1);
else if(*str1 == *str2)
return match(str1+1, str2+1);
return false;
}
int main()
{
char str1[100], str2[100];
while(cin>>str1>>str2)
{
if(match(str1, str2))
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
return 0;
}