算法竞赛入门经典 3.1 数组

//3.1 数组
//程序3-1 逆序输出
#include<iostream>
using namespace std;
const int MAX=100+10;		//据说这样声明,是为了保险
int a[MAX];

int main()
{
	int i,x,n=0;
	while(cin>>x)
		a[n++]=x;		//将每一个值赋给数组,下标每次增加1
	for(i=n-1;i>=1;i--)	 //逆序输出
		cout<<a[i]<<" "<<endl;
	cout<<a[0]<<endl;
	return 0;
}



//程序3-2 开灯问题
/*
*有n盏灯,编号为1~n。第1个人把所有灯打开,第2个人按下所有编号为2的倍数的开关
*(这些灯将被关掉),第3个人按下所有编号为3的倍数的开关(其中关掉的灯被打开,开着的灯被关闭)
*依次类推。一共有k个人,问最后有哪些灯是亮着的?
*输入:n和k,输出开着的灯编号。k<=n<=1000
*样例输入:7 3
*样例输出:1 5 6 7
*/
#include<iostream>
#include<cstring>
using namespace std;
const int MAX=1000+10;
int a[MAX];

int main()
{
	int i,j,n,k,first=1;	
	memset(a,0,sizeof(a));     //作用是把数组a清零
	cin>>n>>k;
	for(i=1;i<=k;i++)
		for(j=1;j<=n;j++)
			if(j%i==0) a[j]=!a[j];
	for(i=1;i<=n;i++)
		if(a[i])
		{
			if(first) first=0;
			else cout<<" ";
			cout<<i;
		}
		cout<<endl;
		return 0;
}



//例题3-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
*/

#include<iostream>
#include<cstring>
using namespace std;
const int MAX=10;
int a[MAX][MAX];

int main()
{
	int n,x,y,tot=0;
	cin>>n;
	memset(a,0,sizeof(a));		//清零
	tot=a[x=0][y=n-1]=1;		//第一个数从1开始填,位置为x=0,y=n-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][y]=++tot;	//向上填数
		while(y+1<n && !a[x][y+1]) a[x][++y]=++tot; //向右填数
	}
	for(x=0;x<n;x++)
	{
		for(y=0;y<n;y++)
			cout<<a[x][y]<<" ";
		cout<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小巫技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值