【算法竞赛入门经典】第三章:数组和字符串 代码和笔记

版权声明:置顶文章如需转载请联系作者 https://blog.csdn.net/Bonstoppo/article/details/79164129

例1:倒序输出(P37)

    代码过于简单,就不贴了。数组放在外面可以开的很大。

例2:开灯问题(P39)

#include<stdio.h>
#include<string.h>
#define max 1010
int a[max];
int main()
{
	int n,k,first=1,i,j;//标志变量first// 
	memset(a,0,sizeof(a));//更新函数memset,在string.h下// 
	scanf("%d%d",&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
	    	    printf(" ");
	    	printf("%d",i);
		}
	printf("\n");
	return 0;
 } 
三点:1.memset。2.标志变量first。3.输出问题。

例3:蛇形填数(P40)

#include<stdio.h> 
#include<string.h>
#define max 20
int a[max][max];
int main()
{
	int n,x,y,tot=0;
    scanf("%d",&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][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++)
		    printf("%3d",a[x][y]);//右对齐,三格// 
		printf("\n");
	}
	return 0;
}

while语句嵌套那个地方做的极为巧妙,向下向右向上向左。

竞赛题目选讲:

例1:TeX中的引导

#include<stdio.h>
int main()
{
	int q=1;
	char c;
	while((c=getchar())!=EOF)
	{
		if(c=='"'){
		    printf("%s",q?"\\":"//");//这个地方注意是%s,不是%c,因为这是两个字母// 
		    q=!q;
		}
		else printf("%c",c);
	}
	return 0;
}


笔记:1.注意EOF,这个是输入结束的标志,只要不是结束,就可以一直输入下去。2.在中间的printf那里是%s而不是%c,这个地方是两个字符。

猜你喜欢

转载自blog.csdn.net/Bonstoppo/article/details/79164129