第一题:
代码:
第一种树形访问结构
#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
#include<iostream>
#include<set>
#include<string>
using namespace std;
int max_hard;
int all_star;
void get_max_hard(vector<pair<int,int>>&data,int now,int total_cost,int has_hard){
for (int i = now; i < data.size(); i++){
if (now<data.size() && total_cost + data[i].first <= all_star){//没有超过水晶之和
int total = total_cost + data[i].first;
int now_hard = has_hard + data[i].second;
if (now_hard > max_hard)max_hard = now_hard;
get_max_hard(data, now + 1, total, now_hard);
}
}
}
int main(){
//ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");
int star, card;
int cost, hard;
vector<pair<int, int>>data;
while (cin>>star>>card){
for (int i = 0; i < card; i++){
cin >> cost >> hard;
data.push_back(make_pair(cost, hard));
}
max_hard = 0;
all_star = star;
get_max_hard(data,0,0,0);
cout<<max_hard<<endl;
data.clear();
}
}
第二种树形访问结构:
#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
#include<iostream>
#include<set>
#include<string>
using namespace std;
int max_hard;
int all_star;
void get_max_hard(vector<pair<int,int>>&data,int now,int total_cost,int has_hard){
int now_hard=0, now_cost;
if (has_hard > max_hard)max_hard = has_hard;
if (now < data.size() && total_cost + data[now].first <= all_star){
//选择当前结点
now_hard = has_hard + data[now].second;
get_max_hard(data,now+1,total_cost+data[now].first,now_hard);
}
//不选择当前结点
if (now < data.size() && total_cost<= all_star){
now_hard = has_hard;
get_max_hard(data,now+1,total_cost,now_hard);
}
}
int main(){
//ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");
int star, card;
int cost, hard;
vector<pair<int, int>>data;
while (cin>>star>>card){
for (int i = 0; i < card; i++){
cin >> cost >> hard;
data.push_back(make_pair(cost, hard));
}
max_hard = 0;
all_star = star;
get_max_hard(data,0,0,0);
cout<<max_hard<<endl;
data.clear();
}
}
第二题:
第二题就相当于是有n阶楼梯,每次至多上3阶,总共有多少种方法:
#include <iostream>
#include <cstring>
using namespace std;
int a[31] = { 0 };
int main()
{
int n;
cin >> n;
a[1] = 1;
a[2] = 2;
a[3] = 4;
for (int i = 4; i <= n; i++)
{
a[i] = a[i - 1] + a[i - 2] + a[i - 3];
}
cout << a[n] << endl;
return 0;
}