求解《百钱百鸡》问题
1只公鸡5元 1只母鸡3元 3只小鸡1元 用100元买100只鸡
问公鸡 母鸡 小鸡各有多少只
for x in range(0, 20):
for y in range(0, 33):
for z in range(0,300):
if 5 * x + 3 * y + z / 3 == 100 and x+y+z==100:
print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z))
循环过多稍微优化一下
for x in range(0, 20):
for y in range(0, 33):
z = 100 - x - y
if 5 * x + 3 * y + z / 3 == 100:
print('公鸡: %d只, 母
鸡: %d只, 小鸡: %d只' % (x, y, z))
我们继续优化,
x+y+z=100
5x+3y+z/3=100 联立我们先消去z ,7x+4y=100,可解得y=(100-7x)/4
for x in range(0, 20):
y=(100-7*x)/4
z=100-x-y
if z%3==0 and y>=0 and z>=0:
print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z))
求矩阵的两对角线上的元素之和
#include<bits/stdc++.h>
using namespace std;
int n,a[1000][1000],s;
int main()
{ cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(abs(i-j)==0||abs(i+j)==n-1)
s+=a[i][j];
cout<<s;
return 0;
}
这题主要还是找规律,很容易得出。
上面的题目还是很简单的,但是一些稍微麻烦点的题会涉及排序问题,我这边简单的讲一下C++的sort用法。
先从最简单的排序开始,见代码
#include<bits/stdc++.h>
using namespace std;
int a[10];
int main()
{ for(int i=0;i<10;i++)
cin>>a[i];
sort(a,a+10);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
输入:10 2 3 5 4 8 9 7 11 20
输出:2 3 4 5 7 8 9 10 11 20
默认是从小到大排序的,当然我们也可以让他从大到小排序。
下面给出两种方法
法一:
#include<bits/stdc++.h>
using namespace std;
int a[10];
int main()
{ for(int i=0;i<10;i++)
cin>>a[i];
sort(a,a+10,greater<int>());
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
输入:10 2 3 5 4 8 9 7 11 20
输出:20 11 10 9 8 7 5 4 3 2
法二:`
#include<bits/stdc++.h>
using namespace std;
int a[10];
int cmp(int a,int b)
{ return a>b;
}
int main()
{ for(int i=0;i<10;i++)
cin>>a[i];
sort(a,a+10,cmp);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
```
输入:10 2 3 5 4 8 9 7 11 20
输出:20 11 10 9 8 7 5 4 3 2
sort讲到这里,下次我会直接拿真题开刀讲解
8 分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复