算法实现题 2-5 半数集问题

360 篇文章 3 订阅
88 篇文章 5 订阅

´问题描述:
给定一个自然数 n,由 n 开始可以依次产生半数集 set(n)中的数如下。
(1) n∈set(n);
(2) 在 n 的左边加上一个自然数,但该自然数不能超过最近添加的数的一半;
(3) 按此规则进行处理,直到不能再添加自然数为止。
例如,set(6)={6,16,26,126,36,136}。半数集 set(6)中有 6 个元素。
注意半数集是多重集。
´编程任务:
对于给定的自然数 n,编程计算半数集 set(n)中的元素个数。
代码:

#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set> 
#include<unordered_map> 
#include<fstream>
using namespace std;
int a[1000];
int comp(int n);
int comp(int n){
	int ans=1;
	if(a[n]>0){
		return a[n];
	}
	for(int i=1;i<=n/2;i++){
		ans+=comp(i);
	}
	a[n]=ans;
	return ans;
}
int main(){
    int n;
	cin>>n;
	cout<<comp(n);
}

文件读写输出

#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set> 
#include<unordered_map> 
#include<fstream>
using namespace std;
int a[1000];
int comp(int n);
int comp(int n){
	int ans=1;
	if(a[n]>0){
		return a[n];
	}
	for(int i=1;i<=n/2;i++){
		ans+=comp(i);
	}
	a[n]=ans;
	return ans;
}
int main(){
	int n,x;
	fstream infile("input.txt",ios::in);
	ofstream outf;
	outf.open("output.txt");
	while(!infile.eof()){
		infile>>x;
		outf<<comp(x)<<endl;
	}
	outf.close();
	infile.close();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_努力努力再努力_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值