写这两个题来反思一下自己……
tyvj1083:
昨天做这个题的时候为什么一直想的是深搜啊= =还好今天写了一下一次就过了………我感觉确实好久没有好好的做一些基础题了…………
广搜找最长的路径,因为给的数据比较大,二维数组开不下,就用了vector
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
struct node
{
int num, step;
};
queue<node> q;
bool vis[100010];
vector <int> map[100010];
int n, p, c, m;
int bfs()
{
int max = 0;
int i;
node e = {c, 1};
q.push(e);
while(!q.empty())
{
e = q.front();
q.pop();
for(i = 0; i < map[e.num].size(); i++)
{
node e1;
if(vis[map[e.num][i]] == 0)
{
vis[map[e.num][i]] = 1;
e1.num = map[e.num][i];
e1.step = e.step + 1;
//printf("num = %d, step = %d\n", e1.num, e1.step);
if(max < e1.step)
max = e1.step;
q.push(e1);
}
}
}
// printf("max = %d\n", max);
return max;
}
int main (void)
{
while(scanf("%d %d %d", &n, &p, &c) != EOF)
{
memset(vis, 0, sizeof(vis));
vis[c] = 1;
scanf("%d", &m);
int i, a, b;
for(i = 0; i < p; i++)
{
scanf("%d %d", &a, &b);
map[a].push_back(b);
map[b].push_back(a);
}
printf("%d\n", bfs() + m);
for(i = 0; i < 100010; i++)
if(!map[i].empty())
map[i].clear();
}
return 0;
}
tyvj1117:
还是广搜,用到优先队列,跟坦克大战是一个题,发现优先队列都忘了怎么写了(打脸)
刚开始没用优先队列,然后写了半天发现不对= =还有就是地图输入的时候,本来是一个字符一个字符的读入,每行结尾用getchar吸收回车,但是貌似数据不是特别严格的样子,一直都是20分,后来改成同%s 一次读入一整行就A了
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x, y;
int time;
friend bool operator < (const node &s1, const node &s2)
{
return s1.time > s2.time;
}
};
priority_queue <node> q;
node start;
char map[30][30];
bool vis[30][30];
int s[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int t, xx, yy;
int bfs()
{
int i;
node e;
start.time = 0;
q.push(start);
while(!q.empty())
{
e = q.top();
q.pop();
if(map[e.x][e.y] == 'm')
return e.time;
for(i = 0; i < 4; i++)
{
int x1 = e.x + s[i][0];
int y1 = e.y + s[i][1];
if(x1 >= 0 && x1 < yy && y1 >= 0 && y1 < xx && map[x1][y1] != 'o' && !vis[x1][y1])
{
vis[x1][y1] = 1;
node e1;
e1.x = x1;
e1.y = y1;
if(map[x1][y1] == '#')
e1.time = e.time + 2;
else
e1.time = e.time + 1;
q.push(e1);
}
}
}
return -1;
}
int main (void)
{
scanf("%d %d %d", &t, &xx, &yy);
//getchar();
memset(vis, 0, sizeof(vis));
int i, j;
for(i = 0; i < yy; i++)
{
scanf("%s", map[i]);
for(j = 0; j < xx; j++)
{
//scanf("%c", &map[i][j]);
if(map[i][j] == 's')
{
start.x = i;
start.y = j;
vis[i][j] = 1;
}
}
//getchar();
}
int ok = bfs();
if(ok == -1 || ok >= t)
printf("55555\n");
else
printf("%d\n", ok);
return 0;
}