图形-CSDN博客

43 阅读1分钟

while(cin ....)只能够读入一个例子,while(~scanf())可以读到文件结束,亲测。

读入整数时,后面的回车键留在键盘缓冲区,若接着用gets()读入时,回车键会被其吃掉。

Windows下比较文件命令fc,Linux下diff 或sdiff。

hihocoder 1495 矩形分割

把图形扩大一倍,就可以用深度优先搜索找连通块了,就不会出现平行边那种情况了

2 2

\\

\\

#include <string>
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 207;
bool pic[maxn][maxn];
char str[maxn][maxn], chs[maxn]; 
int dir[8][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1}};
int d2[4][2] = {{-1, -1}, {0, -1}, {0, 0}, {-1, 0}};
void dfs(int x, int y, bool pic[][maxn], int r, int c){
	pic[x][y] = true;
	for (int i= 0; i < 8; ++i) {
		int xx = x + dir[i][0];
		int yy = y + dir[i][1];
		if (xx < 0 || xx > r || yy < 0 || yy > c || pic[xx][yy] == true)
			continue;
		if (i < 4) {
				dfs(xx, yy, pic, r, c);
		}
		else { //斜着 
			int xxx = x + d2[i - 4][0];
			int yyy = y + d2[i - 4][1];
			if (xxx >= 0 && xxx < r && yyy >= 0 && yyy < c && str[xxx][yyy] == ' ')
				dfs(xx, yy, pic, r, c);
		}		
	}	
}
int main() 
{
	freopen("data.out", "r", stdin);
	freopen("myans.txt", "w", stdout);	
	int n, m;
	while(~scanf("%d%d", &n, &m)) {
		getchar();
		memset(pic, 0, sizeof(pic));
		for (int i = 0; i < n; ++i) {
			gets(chs);
			for (int j = 0; j < m; ++j) {
				int i2 = i << 1, j2 = j << 1;
				if (chs[j] == '/') {
					pic[i2 + 2][j2] = pic[i2][j2+2] = pic[i2 + 1][j2 + 1] = true;
					str[i2 + 1][j2] = str[i2][j2 + 1] = '/';
					str[i2][j2] = str[i2 + 1][j2 + 1] = ' ';
				}					
				else if (chs[j] == '\\') {
					 pic[i2][j2] = pic[i2+1][j2+1] = pic[i2 + 2][j2 + 2] = true; 
					 str[i2][j2] = str[i2 + 1][j2 + 1] = '\\';
					 str[i2 + 1][j2] = str[i2][j2 + 1] = ' ';
				}
				else {
					str[i2][j2] = str[i2 + 1][j2 + 1] = str[i2 + 1][j2] = str[i2][j2 + 1] = ' ';
				}
			}
		}
//		for (int i = 0; i < n*2; ++i) {
//			for (int j = 0; j < m*2; ++j)
//				putchar(str[i][j]);
//			puts("");
//		}
//		for (int i = 0; i <= n*2; ++i) {
//			for (int j = 0; j <= m*2; ++j)
//				printf("%d\t", pic[i][j]);
//			puts("");
//		}
		int cnt = 0; 
		for (int i = 0; i <= n*2; ++i)
			for (int j = 0; j <= m*2; ++j)
				if (pic[i][j] == false) {
					cnt++;
					dfs(i, j, pic, n*2, m*2);
				}
		cout << cnt << endl;
	}
	
	return 0;
}

测试函数,生成测试样例\

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
	freopen("data.out", "w", stdout);
	int N = 1000;
	char str[] = "/ \\";
	srand(time(NULL));
	while(N--) {
		int n = rand() % 100 + 1, m = rand() % 100 + 1;
		printf("%d %d\n", n, m);
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < m; ++j) {
				putchar(str[rand() % 3]);
			}
			puts("");
		}
		puts("");
	}
	
	return 0;
} 


图形分享

\

\