算法竞赛入门经典 3.1 数组

来源:互联网 发布:网络信息采集软件 编辑:程序博客网 时间:2024/05/29 18:07
//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;//将每一个值赋给数组,下标每次增加1for(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-1while(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;}

原创粉丝点击