算法實現之戰車問題

   與拉斯維加斯算法 和  n後問題中的拉斯維加斯算法類似。在n×n格的棋盤上隨機放置彼此不受攻擊的車

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
ifstream fin("input.txt");

void init(int n) //初始化計算
{
	int i, j, k, x, y;
	state = new int[n * n + 2];
	Make2DArray(link, n * n + 1, 2 * n + 1);
	state[0] = -1;
	state[n * n + 1] = -1;
	for (int no = 1; no <= n * n; no++)
	{
		i = (no - 1) / n;
		j = (no - 1) % n;
		link[no][0] = 0;
		state[no] = -1;
		if (row[i][j] == '.')
		{
			state[no] = 0;
			k = 0;
			y = j;
			while ((y < n - 1) && (row[i][y + 1] == '.'))
			{
				link[no][0]++;
				y++;
				k++;
				link[no][k] = i * n + y + 1;
			}
			y = j;
			while ((y > 0) && (row[i][y - 1] == '.'))
			{
				link[no][0]++;
				y--;
				k++;
				link[no][k] = i * n + y + 1;
			}
			x = i;
			while ((x < n - 1) && (row[x + 1][j] == '.'))
			{
				link[no][0]++;
				x++;
				k++;
				link[no][k] = x * n + j + 1;
			}
			x = i;
			while ((x > 0) && (row[x - 1][j] == '.'))
			{
				link[no][0]++;
				x--;
				k++;
				link[no][k] = x * n + j + 1;
			}
		}
	}
}

int main()
{
	int n;
	randomNumber rnd;
	fin >> n;
	for (int i = 0; i < n; i++)
		fin >> row[i];
	init(n);
	int max = 0, rept = 0, put = 0;
	while (rept < 100000)
	{
		rept++;
		int count = 0;
		while (true)
		{
			int x = rnd.random(n * n) + 1, c = x;
			while ((x <= n * n) && (state[x] != put))
				x++;
			if (state[x] != put)
			{
				x = c;
				while ((x > 0) && (state[x] != put))
					x--;
			}
			if (state[x] == put)
			{
				count++;
				for (i = 1; i <= link[x][0]; i++)
					if (state[link[x][i]] == put)
						state[link[x][i]]++;
				state[x]++;
			}
			else
				break;
		}
		if (count > max)
			max = count;
		put++;
	}
	cout << max << endl;
	return 0;
}

 

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