目录
第一题-Pre-Post
思路:
#include<iostream>
using namespace std;
//计算可能性
long long num(string& str1, string str2, int left1, int right1, int left2, int right2, int m)
{
//如果前序结束返回1
if (left1 == right1)
return 1;
int nums = 0;
long long mul = 1;//阶乘值
int Left1=left1+1, Right1=left1+1;
int Left2=left2, Right2=left2-1;
while (Left1 <= right1)
{
nums++;
Right2=str2.find(str1[Left1]);
int cur = Left2;
while (cur < Right2)
{
Right1++;
cur++;
}
mul *= num(str1, str2, Left1 , Right1, Left2, Right2 , m);
Left1 = Right1 + 1;
Right1 = Left1;
Left2 = Right2 + 1;
}
for (int i = m; i > m - nums; i--)
{
mul *= i;
}
for (int i = 1; i < 1 + nums; i++)
{
mul /= i;
}
return mul;
}
int main()
{
int m;
string str1;//前序
string str2;//后序
while (cin >> m >> str1 >> str2)
{
if (str1.size() == 1)
cout << 1 << endl;
else
cout << num(str1, str2,0,str1.size()-1,0,str2.size()-1,m) << endl;
}
return 0;
}
第二题-Rational Arithmetic
思路:
- 约分reduction时,gcd要加绝对值
- 分数的分子分母相乘的时候两个int相乘容易超界,所以全部用long long
- 假分数和带分数的转换输出可以先用假分数的分子分母判断,再转换输出,而不是直接得到整数部分再判断整数部分,那样情况太多。
#include <iostream>
#include <algorithm>
using namespace std;
//分数结构体
struct Fraction
{
long long up;//分子
long long down;//分母
};
//求出最大公约数
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
Fraction reduction(Fraction a) {
//分母小于0,翻转分子分母
if (a.down < 0) {
a.up = -a.up;
a.down = -a.down;
}
//分子等于0,将分母置1
if (a.up == 0) {
a.down = 1;
}
else {
long long d = abs(gcd(a.up, a.down));
a.up /= d;
a.down /= d;
}
return a;
}
Fraction add(Fraction& a, Fraction& b) {
Fraction res;
res.up = a.up * b.down + a.down * b.up;
res.down = a.down * b.down;
return reduction(res);
}
Fraction sub(Fraction& a, Fraction& b) {
Fraction res;
res.up = a.up * b.down - a.down * b.up;
res.down = a.down * b.down;
return reduction(res);
}
Fraction multi(Fraction& a, Fraction& b) {
Fraction res;
res.up = a.up * b.up;
res.down = a.down * b.down;
return reduction(res);
}
Fraction div(Fraction& a, Fraction& b) {
Fraction res;
if (b.up == 0) {
res.down = 0;
res.up = 1;
return res;
}
res.up = a.up * b.down;
res.down = a.down * b.up;
return reduction(res);
}
void transPrint(Fraction& a) {
if (a.down == 0) {
printf("Inf");
return;
}
if (a.up < 0) {
printf("(");
}
if (a.down == 1) {
printf("%lld", a.up);
}
else if (abs(a.up) > a.down)
{
printf("%lld %lld/%lld", a.up / a.down, abs(a.up) % a.down, a.down);
}
else {
printf("%lld/%lld", a.up, a.down);
}
if (a.up < 0) {
printf(")");
}
}
int main() {
Fraction a, b;
char op[4] = { '+','-', '*', '/' };
scanf("%lld/%lld %lld/%lld", &a.up, &a.down, &b.up, &b.down);
a = reduction(a);
b = reduction(b);
Fraction res;
for (int i = 0; i < 4; i++)
{
switch (i) {
case 0:
res = add(a, b); break;
case 1:
res = sub(a, b); break;
case 2:
res = multi(a, b); break;
case 3:
res = div(a, b); break;
default:
break;
}
transPrint(a);
printf(" %c ", op[i]);
transPrint(b);
printf(" = ");
transPrint(res);
printf("\n");
}
return 0;
}