【915程序设计】18西交大软件专硕915程序设计真题讲解

发布于:2022-12-19 ⋅ 阅读:(163) ⋅ 点赞:(0)

1. 数字统计

#include<bits/stdc++.h>
using namespace std;

string str;
int cnt[10];

int main(){
	cin>>str;
	for(int i=0;i<str.length();++i){
		char ch=str[i];
		if(ch-'0'>=0&&ch-'0'<=9){
			++cnt[ch-'0'];
		}
	}
	for(int i=0;i<10;++i){
		cout<<i<<":"<<cnt[i];
		if(i!=9){
			cout<<", ";
		}
	}
	return 0;
}

在这里插入图片描述

2. 姓名成绩稳定排序

#include<bits/stdc++.h>
using namespace std;

typedef struct{
	string name;
	int score;
}student;

bool rule(student a,student b){
	return a.score>b.score;
}


int n;

int main(){
	cin>>n;
	student stu[n];
	for(int i=0;i<n;++i){
		cin>>stu[i].name>>stu[i].score;
	}
	sort(stu,stu+n,rule);
	for(int i=0;i<n;++i){
		cout<<stu[i].name<<stu[i].score<<endl;
	}
	return 0;
}

在这里插入图片描述

3. 闰年

#include<bits/stdc++.h>
using namespace std;

int N;
int year,month,day;
//普通闰年: 公历年份是4的倍数, 且不是100的倍数的, 为闰年(如2004年、2020年等就是闰年)
//世纪闰年: 公历年份是整百数的 , 必须是400的倍数才是闰年(如1900年不是闰年,2000年是闰年)
int leapYear[]={0,31,29,31,30,31,30,31,31,30,31,30,31};		//一年366天 
int commonYear[]={0,31,28,31,30,31,30,31,31,30,31,30,31};	//一年365天 

int main(){
	cin>>year>>month>>day;
	bool flag=(year%4==0&&year%100!=0)||(year%400==0);
	
	for(int i=0;i<month;++i){
		if(flag){
			N+=leapYear[i];
		}else{
			N+=commonYear[i];
		}
	}
	N+=day;
	cout<<N;	
	return 0;
}

在这里插入图片描述

4. 箱子小球

M个相同的小球,放入N个相同的箱子,允许有的箱子空,求共有多少种分配的方法(箱子不区分先后顺序,如有6个球,123和321是同一种放法)。

#include<bits/stdc++.h>
using namespace std;

int M,N;	//M个小球, N个箱子 
int cnt;

//共N个箱子, 目前还剩下M个小球 , 现在往第i个箱子放小球, 上一个箱子放了num个小球
void f(int i,int num,int M,vector<int> alloc,int N){
	if(i==N){
		if(M==0){
			for(int k=0;k<alloc.size();++k){
				cout<<alloc[k]<<" ";
			}
			cout<<endl;
			++cnt;
		}
		return;
	}
	for(int k=num;k<=M;++k){
		alloc.push_back(k);
		f(i+1,k,M-k,alloc,N);
		alloc.pop_back();
	}
}

int main(){
	cin>>M>>N;	//M个小球, N个箱子 
	vector<int> alloc;
	f(0,0,M,alloc,N);
	cout<<cnt;
	return 0;
}

在这里插入图片描述