USACO Home on the Range

參考USACO,使用的動態規劃 http://www.nocow.cn/index.php/USACO/range

代碼

/*    
ID: wangxin12    
PROG: range
LANG: C++    
*/

#include <iostream>
#include <fstream>
#define MAX 253

using namespace std;

ofstream fo("range.out");
ifstream fi("range.in");

int N;  // 1 < N <= 250
int map[MAX][MAX];
int num[MAX];

void readData() {
	fi>>N;
	int i, j;
	for(i = 1; i <= N; i++) {
		for(j = 1; j <= N; j++) {
			char c;
			fi>>c;
			if(c == '0')
				map[i][j] = 0;
			else if(c == '1')
				map[i][j] = 1;
		}
	}
}

int getMin(int a, int b, int c) {
	int tmp;
	if(a < b) tmp = a;
	else tmp = b;

	if(tmp < c) return tmp;
	else return c;
}

void calculte() {
	int i, j, k;
	for(i = N - 1; i >= 1; i--)
		for(j = N - 1; j >= 1; j--) {
			if(map[i][j])
				map[i][j] = getMin(map[i + 1][j], map[i][j + 1], map[i + 1][j + 1]) + 1;
		}

	for(i = 1; i <= N; i++)
		for(j = 1; j <= N; j++)
			for(k = 2; k <= map[i][j]; k++)
				num[k]++;
}


void output() {
	for(int i = 2; i <= N; i++) {
		if(num[i])
			fo << i << " " << num[i] << endl;
	}
}

int main() {
	readData();

	calculte();

	output();

	//cout << "Hello" << endl;
	fo.close();
	fi.close();
	return 0;
}


我的第一次代碼在test 7 (所有數據全是1)超時,倒是能算出正確答案了。

/*    
ID: wangxin12    
PROG: range   
LANG: C++    
*/

#include <iostream>
#include <fstream>
#define MAX 253

using namespace std;

ofstream fo("out.txt");
ifstream fi("in.txt");

int N;  // 1 < N <= 250
int map[MAX][MAX];
int num[MAX];

void readData() {
	fi>>N;
	int i, j;
	for(i = 1; i <= N; i++) {
		for(j = 1; j <= N; j++) {
			char c;
			fi>>c;
			if(c == '0')
				map[i][j] = 0;
			else if(c == '1')
				map[i][j] = 1;
		}
	}
}

bool extend(int row, int col) {
	int len = map[row][col];
	int i, j, x = 0, y = 0;
	for(i = row + len, j = col; j < col + len + 1; j++) {
		if(map[i][j]) x++;
	}
	if(x != len + 1) return false;

	for(i = row, j = col + len; i < row + len + 1; i++) {
		if(map[i][j]) y++;
	}

	if(y != len + 1)
		return false;
	 
	return true;
}

void calculate(int index) {
	if(index >= MAX) return;

	for(int i = 1; i < MAX; i++)
		for(int j = 1; j < MAX; j++) {
			if(map[i][j] == index) {
				if(extend(i,j)) {
					map[i][j]++;
					num[index + 1]++;
				}		
			}
		}
}

void output() {
	for(int i = 2; i <= N; i++) {
		if(num[i])
			fo << i << " " << num[i] << endl;
	}
}

int main() {
	readData();

	for(int t = 1; t <= N; t++)
		calculate(t);

	output();

	//cout << "Hello" << endl;
	fo.close();
	fi.close();
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章