问题求解与程序设计的三道例题

题目链接

1056.扫雷游戏

1406.凯撒密码

1664.Top K different numbers

1056.扫雷游戏

这题是我准备的,所以比较清楚一点,简单的遍历搜索。

#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <queue>
#include <string.h>
using namespace std;
struct p
{
	int x,y;
}lei[100005];

int n,m;
char chess[105][105];
int go[10][3] = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};

void bfs(int x0,int y0)
{
	p beg,bet;
	beg.x = x0;
	beg.y = y0;
	
	int i,j;
	for(i = 0; i < 8; i++)
	{
		bet.x = beg.x + go[i][0];
		bet.y = beg.y + go[i][1];
		
		if(bet.x > 0 && bet.x <= n && bet.y > 0 && bet.y <= m)
		{
			if(chess[bet.x][bet.y] == '*')continue;
			else
			{
				chess[bet.x][bet.y]++;
			}
		}
	}
}

int main()
{
	int i,j;
	while(scanf("%d%d",&n,&m) != EOF)
	{
		if(n == 0 || m == 0)break;
		
		getchar();
		memset(chess,'0',sizeof(chess));
		int tot = 1;
		for(i = 1; i <= n ; i++)
		{
			for(j = 1; j <= m; j++)
			{
				scanf("%c",&chess[i][j]);
				
				if(chess[i][j] == '*')
				{
					lei[tot].x = i;
					lei[tot++].y = j;
				}
				else
				{
					chess[i][j] = '0';
				}
			}
			getchar();
		}
		
		for(i = 1; i < tot; i++)
		{
			bfs(lei[i].x,lei[i].y);
		}
		
		for(i = 1; i <= n; i++)
		{
			for(j = 1; j <= m; j++)
			printf("%c",chess[i][j]);
			
			printf("\n");
		}
		
		printf("\n");
	}
	return 0;
}


1406.凯撒密码

简单的字符串处理。

#include <string>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
using namespace std;
char s[105];
int main()
{
	int i,j;
	while(gets(s))
	{
		for(i = 0; i < strlen(s) ; i++)
		{
			if((s[i] >= 'D' && s[i] <= 'Z') || (s[i] >= 'd' && s[i] <= 'z'))
			{
				s[i] -= 3;
			}
			else if(s[i] == 'A' || s[i] == 'B' || s[i] == 'C' 
			|| s[i] == 'a' || s[i] == 'b' || s[i] == 'c')
			{
				s[i] += 23;
 			}
 			else
 			continue;
		}
		
		puts(s);
	}
	return 0;
}

1664.Top K different numbers

sort快排。

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string.h>
using namespace std;
int a[10005];
int store[10005];
int main()
{
	int i,j;
	int n,k;
	while(scanf("%d%d",&n,&k) != EOF)
	{
		memset(a,0,sizeof(a));
		memset(store,0,sizeof(store));
		
		for(i = 1; i <= n; i++)
		{
			scanf("%d",&a[i]);
		}
		
		sort(a+1,a+n+1);
		
		int tot = 1;
		store[1] = a[n];
		for(i = n-1 ; i >= 1 ; i--)
		{
			if(a[i] != store[tot])
			{
				tot++;
				store[tot] = a[i];
			}
			
			if(tot == k)break;
		}
		
		if(tot < k)
		{
		    printf("-1\n");	
		    continue;
		}
		
		for(i = k; i >= 1; i--)
		{
			if(i != 1)
			printf("%d ",store[i]);
			else
			printf("%d\n",store[i]);
		}
	}
	return 0;
}
posted @ 2016-05-16 17:24  Wasdns  阅读(217)  评论(0编辑  收藏  举报