### 第十三届蓝桥杯省赛 C++ B组 题目及题解
#### 试题 A: 空间
对于空间问题,通常涉及计算几何或简单的数学运算。具体到此题,可能涉及到三维坐标系中的距离计算或其他基本的空间关系处理。
```cpp
#include <iostream>
using namespace std;
int main() {
double x1, y1, z1;
double x2, y2, z2;
cin >> x1 >> y1 >> z1;
cin >> x2 >> y2 >> z2;
double distance = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1));
cout << fixed << setprecision(2) << distance << endl;
return 0;
}
```
[^1]
#### 试题 B: 卡片
卡片问题一般考察的是组合数学的知识点或者是字符串操作技巧。这类题目往往需要理解排列组合原理以及如何高效地遍历所有可能性来找到最优解法。
```cpp
#include <bits/stdc++.h>
using namespace std;
string cards[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"};
vector<string> deck(cards, end(cards));
void shuffleDeck(vector<string>& d){
random_shuffle(d.begin(),d.end());
}
int main(){
srand(time(NULL)); // 初始化随机数种子
do{
shuffleDeck(deck);
for(auto card : deck)
cout<<card<<" ";
cout<<"\n";
}while(getchar()!='q');
return 0;
}
```
[^2]
#### 试题 C: 直线
直线问题是关于解析几何的基础应用之一,比如求两条直线交点、判断两直线平行与否等问题。解决此类问题的关键在于掌握好斜率的概念及其相关性质的应用方法。
```cpp
struct Line {
double a,b,c; // ax+by+c=0 形式的系数表示一条直线
};
bool isParallel(Line l1,Line l2){
return abs(l1.a*l2.b-l1.b*l2.a)<EPSILON;
}
pair<double,double> intersectionPoint(Line l1,Line l2){
double det=l1.a*l2.b-l1.b*l2.a;
if(abs(det)>EPSILON){ // 不平行则有唯一交点
double px=(l2.c*l1.b-l1.c*l2.b)/det;
double py=(l1.c*l2.a-l2.c*l1.a)/det;
return make_pair(px,-py); // 注意这里返回的纵坐标取负号是因为我们定义方程时c项前面带了个减号
}
throw runtime_error("Lines are parallel or coincident");
}
```
[^3]
#### 试题 D: 货物摆放
货物摆放示例展示了动态规划算法的实际应用场景。通过构建状态转移表并逐步填充表格中的值直到最终得到全局最优解的过程体现了该类问题的核心思想——分治策略下的最优化选择。
```cpp
const int MAXN=1e5+5;
long long dp[MAXN],w[MAXN];
for(int i=1;i<=n;++i){
for(int j=m;j>=v[i];--j){
dp[j]=max(dp[j],dp[j-v[i]]+w[i]);
}
}
cout<<dp[m]<<endl;
```
#### 试题 E: 路径
路径寻找属于图论范畴内的经典难题,无论是广度优先搜索还是深度优先搜索都能很好地解决问题;而当引入权重概念之后,则可以考虑采用Dijkstra算法或是Floyd-Warshall等更高级别的解决方案来进行分析解答。
```cpp
// 使用队列实现BFS查找最短路径长度
queue<int> q;
memset(dist,INF,sizeof dist);
dist[s]=0;q.push(s);
while(!q.empty()){
int u=q.front();q.pop();
for(int v:g[u]){
if(dist[v]==INF){
dist[v]=dist[u]+1;
pre[v]=u;
q.push(v);
}
}
}
if(dist[t]!=INF){
vector<int> path;
for(int cur=t;cur!=-1;cur=pre[cur])
path.push_back(cur);
reverse(path.begin(),path.end());
printf("%d\n%d\n",dist[t],path.size()-1);
for(size_t i=0;i<path.size();++i)
printf(i==path.size()-1?"%d\n":"%d ",path[i]);
}else puts("-1"); // 如果无法到达终点就输出-1
```
#### 试题 F: 时间显示
时间转换是一个非常基础但也容易出错的小知识点,尤其是在不同单位之间的相互转化上要特别小心精度丢失的情况发生。下面给出了一种较为通用的时间格式化函数模板供参考学习之用。
```cpp
stringstream ss;
ss<<setfill('0')<<setw(2)<<hour<<':'<<setw(2)<<minute<<':'<<setw(2)<<second;
return ss.str();
```
#### 试题 G: 砝码称重
砝码称重问题可以通过贪心算法快速得出结论。每次选取当前可用的最大重量作为本次测量的标准,这样既能保证准确性又能减少不必要的复杂度提升效率。
```cpp
sort(weights.rbegin(),weights.rend()); // 对砝码按降序排序
double total_weight=accumulate(begin(weights),end(weights),(double)0.0);
double current_sum=0.0;
int count=0;
for(double w:weights){
if(current_sum+w<=total_weight/2.0){
++count;
current_sum+=w;
}else break;
}
printf("%.lf%%\n",(current_sum/(total_weight/2))*100);
```