算法分析与设计(第三版)王红梅 课后习题答案 第三章

1. 如果一个....。求小于n(n<100)的所有与7无关的正整数的平方和。

#include <iostream>
using namespace std;
bool check(int num){
	if(num%7==0) return true;
	while(num){
		int n=num%10;
		if(n==7) return true;
		num/=10;
	}
	return false;
}
int main() {
	int sum=0;
	for(int i=1;i<=100;i++){
		if(!check(i)) sum+=i*i;
	}
	cout<<sum<<endl;
}

2.一元二次方程,求方程根,精确到小数点后5位。

牛顿法解一元二次方程

 

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
double temp(double x,double a,double b,double c){
	double fx=a*x*x+b*x+c;
	double fxp=2*a*x+b;
	return fx/fxp;
}
void solve(double a,double b,double c,double e=0.00001)
{
	double x0=-5;
	double x=x0-temp(x0,a,b,c);
	int i=0;
	while (abs(x - x0) > e)
	{   
		i++;
		x0=x;
		x = x - temp(x,a,b,c);
		if (i > 50){
			break;
		}
	}
	double x01=5;
	double x1=x01-temp(x01,a,b,c);
	int i1=0;
	while (abs(x1 - x01) > e)
	{   
		i1++;
		x01=x1;
		x1 = x1 - temp(x1,a,b,c);
		if (i1 > 50){
			break;
		}
	}
	if(abs(x-x1)>e*10){
		cout<<x<<endl;
		cout<<x1<<endl;
	}else{
		cout<<x<<endl;
	}
}
int main()
{
	double a,b,c;
	cout << "a.b.c"<<endl;
	cin>>a>>b>>c;
	solve(a,b,c);
	return 0;
}

3.凯撒加密

#include<iostream>
#include<string>
using namespace std;
char To(char c,int key){
	if(c<='Z' &&c>='A'){
		c=(c-'A'+key)%26+'A';
	}else if(c<='z' && c>='a'){
		c=(c-'a'+key)%26+'a';
	}else{
		cout<<"error!!"<<endl;
		return ' ';
	}
}
int main()
{
	string word="abcdefghijklmnopqrstuvwxyz";
	int key=3;
	string pwd="";
	cout<<'Z'-'A'<<endl;
	for(int i=0;i<word.length();i++){
		pwd+=To(word[i],key);
	}
	cout<<pwd<<endl;
	return 0;
}

4.校门外的树

路长为L,则这条路上有L+1棵树

区间[s,t)修路挖树修路,不考虑重叠 挖了t-s棵树

方案一

pair<s,t> 每输入一对则进行判断,区间融合,最后计算挖掉的树的数量即可

方案二

数组模拟

5.约瑟夫环,修改3.2.1

将循环条件

while(count<m)更改为

while(i==-1||count<m[i])

m[]数组代表每个人的密码

i==-1是第一次进入,直接进入

r[i]=1;num++;

修改为

if(count==m[i]){
    r[i]=1;num++;
}

6.桥牌

略。

7.输出任意n阶间断折叠方阵

#include<iostream>
#include<string>
using namespace std;
int M[10001][10001];
int main()
{
	int n;
	cin>>n;
	int num=1;
	for(int i=1;i<=n;i++){
		int j;
		for(j=1;j<=i;j++){
			M[j][i]=num++;
		}
		//cout<<j<<endl;
		for(int w=j-2;w>=1;w--) M[j-1][w]=num++;
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cout<<M[i][j]<<' ';
		}
		cout<<endl;
	}
}

8.泊松分酒

12品脱瓶子8品脱瓶子5品脱瓶子
12 00
435
930
903
183
165
660

  • 19
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值