1.网友年龄
题目大意很明显了,直接暴力枚举。
#include<iostream>
using namespace std;
int main() {
int ans = 0;
for (int i = 10; i < 100; i++) {
int a = i;
int b = a/10, c = a % 10;
if (c * 10 + b == a - 27)
ans++;
}
cout << ans;
}
2.生日蜡烛
公差为1的等差数列求哪几项和为236
#include<iostream>
using namespace std;
int main() {
int flag = 0;
for (int x = 1; x < 100; x++) {
for (int n = 1; n < 100; n++) {
if (n * (x * 2 + n - 1) / 2 == 236)
{
cout << x;
flag = 1;
break;
}
}
if (flag)break;
}
}
3.方格填数
首先将0-9的数字先看做2-11,在进行爆搜,此外在判断坐标时,可以用x = 1 + u / 4, y = u - u / 4 * 4 + 1,
如此在进行判断即可。
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int ans = 0;
bool st[15];
int g[5][6];
bool check(int x, int y,int m) {
int dx[8] = { -1, 1, 0, 0, 1, -1, 1, -1 };
int dy[8] = { 0, 0, -1, 1, 1, -1, -1, 1 };
for (int i = 0; i < 8; i++)
if (abs(g[x + dx[i]][y + dy[i]] - m) == 1)return false;
return true;
}
void dfs(int u) {
if (u == 11) {
ans++;
return;
}
for (int i = 2; i <= 11; i++) {
if (!st[i]) {
int x = 1 + u / 4;
int y = u - u / 4 * 4 + 1;
if (check(x, y, i)) {
st[i] = true;
g[x][y] = i;
dfs(u + 1);
g[x][y];
st[i] = false;
}
}
}
}
int main() {
for (int i = 0; i <= 5; i++)
for (int j = 0; j <= 5; j++)
g[i][j] = 0;
dfs(1);
cout << ans << endl;
}
还有一种暴力做法
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int ans = 0;
do
{
if((abs(a[0]-a[1])!=1)&&(abs(a[1]-a[2])!=1)&&(abs(a[3]-a[4])!=1)&&(abs(a[4]-a[5])!=1)&&
(abs(a[5]-a[6])!=1)&&(abs(a[7]-a[8])!=1)&&(abs(a[8]-a[9])!=1)&&
(abs(a[0]-a[4])!=1)&&(abs(a[1]-a[5])!=1)&&(abs(a[2]-a[6])!=1)&&
(abs(a[3]-a[7])!=1)&&(abs(a[4]-a[8])!=1)&&(abs(a[5]-a[9])!=1)&&
(abs(a[0]-a[3])!=1)&&(abs(a[0]-a[5])!=1)&&(abs(a[1]-a[4])!=1)&&
(abs(a[1]-a[6])!=1)&&(abs(a[2]-a[5])!=1)&&(abs(a[4]-a[7])!=1)&&(abs(a[4]-a[9])!=1)&&
(abs(a[3]-a[8])!=1)&&(abs(a[5]-a[8])!=1)&&(abs(a[6]-a[9])!=1))
ans++;
}while(next_permutation(a,a+10));
cout<<ans<<endl;
}
4.寒假作业
又是一道dfs每三个数判断一次,输出结果即可;
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
bool st[15];
int a[15];
int ans;
void dfs(int u) {
if (u == 4) {
if(!(a[1]/a[2]==a[3]&&a[1]%a[2]==0))return ;
}
else if (u == 7) {
if (!(a[4] * a[5] == a[6]))return;
}
else if (u == 10) {
if (!(a[7] - a[8] == a[9]))return;
}
else if (u == 13) {
if (!(a[10] + a[11] == a[12]))return;
else ans++;
}
for (int i = 1; i <= 13; i++) {
if (!st[i])
{
st[i] = true;
a[u] = i;
dfs(u + 1);
st[i] = false;
}
}
}
int main() {
dfs(1);
cout << ans << endl;
}