寒假集训专题一:C++基础

ESAY1:Long Loong


解题思路:
将题目拆分成两部分:输入n的值;基于n的值输出对应数量的‘o’。

#include<iostream>
using namespace std;

int main()
{
	//1、输入n的值 
	int n;
	cin >> n;
	
	//2、输出结果 
	cout << "L";
	while(n--)
	{
		cout << "o";	
	} 
	cout << "ng" <<endl;
	return 0;
}

ESAY2:YES or YES?

image
解题思路:
两种思路可以选择:(个人觉得有点繁琐,但是直接好用)其一是由于这道题给出的字符串长度为3,而各种大小写组合只有8种,我们可以通过枚举8种结果(例如用数组来存储枚举结果一个一个遍历校对来确定输出);其二是将给出字符串全部转化为大(小)写来直接对比得出结果,麻烦点在于如何直接转化字符串。

#include<iostream>
#include<vector>
using namespace std;

void s_toupper( string& str )
{
	//利用toupper()函数来将字符串转化为全大写字符串 
	int n = str.size();
	for( int i = 0; i < n; i++ )
	{
		str[i] = toupper(str[i]);
	}
}

int main()
{
	int n = 0;
	string str;
	cin >> n;
	vector<string> ans;
	while( n-- )
	{
		cin >> str;
		s_toupper(str);
		
		//将结果存储到vector<string>中便于后续输出 
		if( str == "YES" )
		{
			ans.push_back(str);	
		}
		else
		{
			ans.push_back("NO");
		}		
	}
	//输出结果 
	for( auto an: ans )
	{
		cout << an << endl;	
	}
	return 0; 
} 

ESAY3:Even? Odd? G

image
解题思路:
由于奇偶性只跟个位上的有关,我本来想的是直接把输入的数取个位然后判断奇偶性,然而题目中的数字范围超过了int和long long的最大范围,我一开始没注意所以一直出错。到这个程度大的数字只能考虑别的数据类型来存储结果,最后考虑使用字符串来直接调用最后一个字符来判断结果。

#include<iostream>

int main()
{
	//输入数的个数 
	int n;
	std::cin >> n;
	
	while( n-- )
	{
		std::string num;
		std::cin >> num;
		//加入空字符串的判断 
		if( !num.empty() )
		std::cout << ( (num.back() - '0' ) %2 == 0 ? "even" : "odd") << "\n"; 
	}
	return 0;
}

MEDIUM1:Problem Generator

image
解题思路:
由题目我们可以知道,需要的题是把所有题目数目补齐至与轮数相等,所以我们可以记下所有题目的个数,将差值补齐,结果相加得到结果。

#include<iostream>
#include<vector>

class Solution
{
	public:
		//计算需要多少题 
		int P_need( std::string p, int m )
		{
			//先存储每个难度题目的难度 
			int sum = 0;
			std::vector<int> ct(7);
			for( auto s: p )
			{
				//从0开始作为A到最后G计数增加 
				ct[s-'A']++;
			}
			//遍历结果,将不足m的字母差值相加 
			for( auto c: ct )
			{
				sum += std::max(0,m-c);
			}
			return sum;
		}
};

int main()
{
	Solution s;
	int cnt = 0;
	std::cin >> cnt;
	while( cnt-- )
	{
		int n, m;
		std::cin >> n >> m;
		std::string str;
		std::cin >> str;
		std::cout << s.P_need(str,m) << std::endl;
	}
	return 0;
}

MEDIUM2:rules

image
解题思路:
这道题从题意出发首先要判断规则k的符合民意天数,再判断该规则是否合理。
所以我们可以先给每天遵守k规则的人计数,然后与总人数一半比较大小,记录下符合民意的天数,将符合民意的总天数与总天数一半比较大小,判断出该规则是否合理,最后输出结果。

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

int main()
{
	int n,m,k;
	cin >> n >> m >> k;
	int ans = 0;
	
	for( int i = 0; i < m; i++ )
	{
		int cnt = 0;
		for( int j = 0; j < n; j++ )
		{
			//记录每一天遵守k规则的人 
			int x;
			cin >> x;
			if( x == k )
			{
				cnt++;
			}
		}
		//记录下规则k符合民意的天数 
		if( cnt >= ( n + 1 ) / 2 )
		{
			ans++;
		}
	}
	
	//对规则k做合理性判断 
	if( ans >= ( m + 1 ) / 2 )
	{
		cout << "YES" << endl;
	}
	else
	{
		cout << "NO" << endl;
	}
}

学习总结:

虽然有一定的C++基础,但这次的课程仍然使我受益匪浅,比如万能头的使用,还有在上面没有提到的Hard部分题目,讲题时提到的不用管过程,直接考虑结果的做法在一定情形下会解决程序运行的耗时问题,降低程序的时间复杂度,不失为一种好方法。既巩固了基础,还发现了STL容器一些平时不在意的函数和优点,总之,十分受益。

posted @ 2025-01-23 20:50  yeqa  阅读(20)  评论(0)    收藏  举报