Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

之前WA和TLE了好几次,折腾了一天终于AC了,G++提交500MS,BFS+位运算,纪念一下

Posted by lzs12348 at 2012-06-23 11:14:47 on Problem 2965 and last updated at 2012-06-23 11:18:11
之前WA和TLE了好几次,折腾了一天终于AC了,G++提交500MS,BFS+位运算,纪念一下。
在自己电脑上运行是20ms,提交是500ms。
有几点地方要注意下:
1、BFS遍历时候,循环变量为i应该用flip_num[15-i],否则答案不对。
2、位运算最好先把16种要取反运算的值用数组存flip_num起来,否则有可能超时间。

AC code:
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

const int MAX_STATE = 65536;
const int ALL_OPEN = 0;
const int SIZE = 4;

vector<int> state(MAX_STATE, -1), pre(MAX_STATE, -1);
int current_state = 0;  // use the low 16 bits of int 
						// to store the current state in reverse order
int flip_num[16] = {63624,62532,61986,61713,36744,20292,12066,7953,35064,
	           17652,8946,4593,34959,17487, 8751, 4383};

int input(istream& in);
void solve();

int main()
{
	input(cin);
	solve();

	return 0;
}

int convert(char c);   // convert '+' and '-' to 1 and 0
int input(istream& in)
{
	current_state = 0;
	char c;
	for (int i = 0; i < SIZE * SIZE; i++) {
		in >> c;
		current_state += (convert(c) << i);
	}
	return 1;
}

int convert(char c)
{
	if (c == '+')
		return 1;
	else 
		return 0;
}

void process_solution();
void solve()
{
	queue<int> q;
	int next_state;

	state[current_state] = 0;
	q.push(current_state);

	while (!q.empty()) {
		current_state = q.front();  q.pop();
		for (int i = 0; i < SIZE * SIZE; i++) {
			next_state = current_state ^ flip_num[15 - i];
			if (next_state == ALL_OPEN) {
				pre[next_state] = i;
				state[next_state] = state[current_state] + 1;
				process_solution();
				return ;
			}
			if (state[next_state] == -1) {
				state[next_state] = state[current_state] + 1;
				pre[next_state] = i;
				q.push(next_state);
			}
		}
	}
}

void process_solution()
{
	stack<int> s;
	int tmp;

	cout << state[0] << endl;
	for (int i = 0; pre[i] != -1; i ^= flip_num[15 - pre[i]])
		s.push(pre[i]);
	while (!s.empty()) {
		tmp = s.top();  s.pop();
		cout << (tmp / 4 + 1) << " " << (tmp % 4 + 1) << endl;
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator