您的位置:首页 > 其它

hdu 2757 Ocean Currents (一搜到底)

2010-07-23 19:57 253 查看
]/*
看来状态真的很重要,对于很大好的自己想学的东西,在写代码的时候就拼命地用进去,这是你能马上学会的
最快的途径,这个题目一开始以为是一般的BFS,当顺风的时候要一搜到底的,这样就可以避免TLE
*/
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <cmath>
#include <bitset>
using namespace std;
struct node
{
int x, y, step;
node(){};
node(int a, int b, int c) :x(a), y(b), step(c){};
friend bool operator < (node aa, node bb)
{
return aa.step > bb.step;
}
};
const int N = 1005;
int dir[8][2] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};
char map

;
int r, c;
int sx, sy, ex, ey;
bitset <1000005> hash; // 这个hash 内存少很多
//priority_queue<node> Q;
queue<node>Q; // 用队列时间明显快很多
inline int  index(node next)
{
return (next.x - 1) * c + next.y - 1;
}
inline bool ok(node next)
{
if(next.x >= 1 && next.x <= r && next.y >= 1 && next.y <= c && !hash[index(next)])
return true;
return false;
}
inline bool final(node next)
{
if(next.x == ex && next.y == ey)
return true;
return false;
}
void BFS()
{
hash[ index( node(sx, sy, 0) ) ] = true;
node now, next, middle;
while(!Q.empty())
Q.pop();
if(final( node(sx, sy, 0) ) )
{
printf("0/n");
return;
}
Q.push( node(sx, sy, 0));
while(!Q.empty())
{
now = Q.front();
Q.pop();
//hash[now.x][now.y] = true;
int d1 = map[now.x][now.y] - '0';
middle = now;
while(1)
{
next.x = middle.x + dir[d1][0];
next.y = middle.y + dir[d1][1];
if(ok(next))
{ // 有顺风方向的一直找到底
if(final(next))
{
printf("%d/n", next.step);
return ;
}
next.step = middle.step;
hash[index(next)] = true;
Q.push(next);
middle = next;
d1 = map[next.x][next.y] - '0';
}
else
break;
}
int d2;
for(int i = 0; i < 8; i++)
{
if(i == d1)
continue;
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
next.step = now.step + 1;
if(ok(next))
{
middle = next;
d2 = map[next.x][next.y] - '0';
hash[index(next)] = true;
if(final(next))
{
printf("%d/n", next.step);
return ;
}
Q.push(next);
while(1)
{
next.x = middle.x + dir[d2][0];
next.y = middle.y + dir[d2][1];
if(ok(next))
{
if(final(next))
{
printf("%d/n", next.step);
return ;
}
next.step = middle.step;
hash[index(next)] = true;
Q.push(next);
middle = next;
d2 = map[next.x][next.y] - '0';
}
else
break;
}
}

}
}
}
int main()
{
//freopen("hxsh.in", "r", stdin);
while(scanf("%d %d", &r, &c) != EOF )
{
for(int i = 1; i <= r; i++)
{
scanf("%s", map[i] + 1);
}
int n;
scanf("%d", &n);
while(n--)
{
hash.reset();
scanf("%d %d %d %d", &sx, &sy, &ex, &ey);
BFS();
}
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c