文章目录
引例1 开灯问题
题目描述
有n盏灯,编号为1~n。第1个人把所有灯打开,第2个人按下所有编号为2的倍数的开关(这些灯将被关掉),第3个人按下所有编号为3的倍数的开关(其中关掉的灯将被打开,开着的灯将被关闭),依此类推。一共有k个人,问最后有哪些灯开着?输入n和k,输出开着的灯的编号。k≤n≤1000。
样例输入
7 3
样例输出
1 5 6 7
问题分析
令灯灭为0
,灯开为1
,将符合第i
个人的灯‘取反’。
代码
#include <iostream>
#include <cstring>
using namespace std;
#define maxn 1010
int a[maxn];
int main(){
int n, k, first = 1;
memset(a, 0, sizeof(a));
cin >> n >> k;
for(int i=1; i<=k; i++){
for(int j = 1; j<=n; j++)
if(j%i == 0) a[j] = !a[j];
}
//输出结果
for(int i=1; i<=n; i++){
if(a[i]){
if(first) first = 0;//严格控制输出格式,输出的第一个数前不应有空格
else cout << " ";
cout << i;
}
}
cout << endl;
return 0;
}
引例2 蛇形填数
题目描述
在n×n方阵里填入1,2,…,n×n,要求填成蛇形。例如,n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
上面的方阵中,多余的空格只是为了便于观察规律,不必严格输出。n≤8。
问题分析
从起始位置开始先向下,到不能填为止,再向左,到不能填为止,再向上,到不能填为止,最后向右,到不能填为止填入对应的数;
假设方阵初始为零,则转向的条件为走到方阵边界或下一个数不为零;
填完最后一个数n*n结束;
代码
#include <iostream>
#include <cstring>
using namespace std;
#define maxn 20
int a[maxn][maxn];
int main(){
int n, x, y, tot = 0;
cin >> n;
memset(a,0,sizeof(a));
tot = a[x=0][y=n-1] = 1;
while(tot < n*n){
while(x+1<n && !a[x+1][y]) a[++x][y] = ++tot;
while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++tot;
while(x-1>=0 && !a[x-1][y]) a[--x]