最短路径

以外卖问题为例
冬天到了,小伙伴们都懒得出去吃饭了,纷纷打电话叫起了外卖。送外卖的小哥想找出一条最短的路径,小区门口进来,送完外卖又回到小区门口。
整个小区是一个由m*n个边长为1的正方形组成的矩形,各幢公寓楼分布于正方型的顶点上,小区门口位于左上角。每幢楼与相邻的八个方向的楼之间都有道路。
下图为m=2,n=3的小区地图,并且外卖小哥要经过的最短路径为6

法一、
思路:使用 vector 模拟大数乘法。
#include
#include
#include <math.h>
#include
#include
#include
using namespace std;
vector Multi(const vector &a, const vector &b)
{ vector answer(a.size() + b.size());
int answerSize = answer.size();
for (int i = b.size()-1; i >= 0; i–)
{ answerSize = answer.size() - 1 - (b.size() - 1 - i);
for (int j = a.size() - 1; j >= 0; j–)
{ int temp = a[j] * b[i];
if (answer[answerSize] + temp < 10)
answer[answerSize–] += temp;
else {
answer[answerSize-1] += (answer[answerSize] + temp) / 10;
answer[answerSize] = (answer[answerSize] + temp) % 10;
answerSize–;
} } }
return answer;}

int main(){
string m, n;
while (cin >> m >> n)
{ vector a, b;
for (int i = 0; i < m.size(); i++)
{ a.push_back(m[i] - ‘0’); }
for (int i = 0; i < n.size(); i++) {
b.push_back(n[i] - ‘0’); }
if (a[a.size() - 1] % 2 != 0 && b[b.size() - 1] % 2 != 0)
{ vector temp = Multi(a, b);
bool check = (temp[0] == 0 )? true : false;
for (int i = 0; i < temp.size(); i++)
{ if (check)
{ check = false; continue; }
cout << temp[i]; }
cout << “.41”<< endl; }
else { vector temp = Multi(a, b);
bool check = (temp[0] == 0) ? true : false;
for (int i = 0; i < temp.size(); i++)
{ if (check) {
check = false; continue; }
cout << temp[i]; }
cout << “.00” << endl; } }
system(“pause”);}

法二
#include
#include
using namespace std;
string add(string x, string y) { 字符串加法 }
string mul(string x, string y) { 字符串乘法 }
int main() {
string m, n, ans;
while(cin >> m >> n)
{ ans.clear();
ans = mul(m, n);
if((m[m.length()-1]-‘0’) * (n[n.length()-1]-‘0’) % 2 == 0)
{ cout << ans << “.00” << endl; }
else
{ cout << ans << “.41” << endl; } }
return 0; }
法三 最简便的python

while True:
try: m, n = list(map(int, input().split()))
except: break
if m%2 == 0 or n%2 == 0:
print(str(mn)+’.00’)
else:
print(str(m
n)+’.41’)

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值