hdu-3468 Treasure Hunting(BFS+二分匹配)

版权声明:Amove? https://blog.csdn.net/Amovement/article/details/80967249

Treasure Hunting

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 2198    Accepted Submission(s): 598


Problem Description
Do you like treasure hunting? Today, with one of his friend, iSea is on a venture trip again. As most movie said, they find so many gold hiding in their trip.
Now iSea’s clever friend has already got the map of the place they are going to hunt, simplify the map, there are three ground types:

● '.' means blank ground, they can get through it
● '#' means block, they can’t get through it
● '*' means gold hiding under ground, also they can just get through it (but you won’t, right?)

What makes iSea very delighted is the friend with him is extraordinary justice, he would not take away things which doesn’t belong to him, so all the treasure belong to iSea oneself! 
But his friend has a request, he will set up a number of rally points on the map, namely 'A', 'B' ... 'Z', 'a', 'b' ... 'z' (in that order, but may be less than 52), they start in 'A', each time friend reaches to the next rally point in the shortest way, they have to meet here (i.e. iSea reaches there earlier than or same as his friend), then start together, but you can choose different paths. Initially, iSea’s speed is the same with his friend, but to grab treasures, he save one time unit among each part of road, he use the only one unit to get a treasure, after being picked, the treasure’s point change into blank ground.
Under the premise of his friend’s rule, how much treasure iSea can get at most?

 

Input
There are several test cases in the input.

Each test case begin with two integers R, C (2 ≤ R, C ≤ 100), indicating the row number and the column number.
Then R strings follow, each string has C characters (must be ‘A’ – ‘Z’ or ‘a’ – ‘z’ or ‘.’ or ‘#’ or ‘*’), indicating the type in the coordinate.

The input terminates by end of file marker.
 

Output
For each test case, output one integer, indicating maximum gold number iSea can get, if they can’t meet at one or more rally points, just output -1.

 

Sample Input
2 4 A.B. ***C 2 4 A#B. ***C
 

Sample Output
1 2
 

一、原题地址

        点我传送


二、大致题意

    有一个n*m的矩阵,

    字母 表示目标点,

    *  表示一枚金币, 

    .  表示空地可前进

    # 表示障碍步可前进

    现在主人公从A点出发,前往下一个顺序的目标点,(目标点的排序为A……B……C…………a……z,必须依次经过)。他会以最快的方式前往下一个目标点,因为他与同伴有过约定,每一次在前往下一个目标点的最短路中,他可以带走路途中的其中一枚金币。现在询问在到达最后一个目标点时,他最多可以拿到多少金币。


三、大致思路

    在读入地图的过程中我们可以得到目标点的个数,这样就能判断地图上是不是缺少了某些目标点。

    从每个目标点开始跑一次BFS,可以判断是否能达到下一个目标点,若不能达到则输出-1,同时也得到了当前目标点到达下一个目标点的1条或多条最短路。利用DFS往前搜索,从下一个目标点往当前目标点沿着最短路搜回来,若这些路上存在金币,则将当前目标点与这个金币在二分关系中相连,这样表示可以在这条路上取走这枚金币。这样遍历全部的目标点后,就建立了一个完整的二分图。


四、代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
using namespace std;
const int inf = 0x3f3f3f3f;
#define LL long long int 
long long  gcd(long long  a, long long  b) { return a == 0 ? b : gcd(b % a, a); }


int n, m;
char mmp[105][105];
int vis[105][105];
int neednum;

const int maxn = 110;
vector<int> vec[maxn];
int match[maxn*maxn];
int visit[maxn*maxn];

int x[] = { 1,-1,0,0 };
int y[] = { 0,0,1,-1 };
struct Node
{
	int x, y;
}need[55];
int uN;
int dis;
int find(int u)
{
	for (int i = 0; i < vec[u].size(); i++)
	{
		int v = vec[u][i];
		if (!visit[v])
		{
			visit[v] = 1;
			if (match[v] == -1 || find(match[v]))
			{
				match[v] = u;
				return true;
			}
		}
	}
	return false;
}
int Match()
{
	int ans = 0;
	memset(match, -1, sizeof(match));
	for (int i = 0; i < uN - 1; i++)
	{
		memset(visit, 0, sizeof(visit));
		if (find(i))
			ans++;
	}
	return ans;
}
void Pre_DFS(int nx, int ny, int id)
{
	if (vis[nx][ny] == 1)
	{
		return;
	}
	if (mmp[nx][ny] == '*')
	{
		vec[id].push_back(nx * m + ny);
		//printf("add    from: %d    to: %d \n", id , nx * m + ny);
		/*DC.AddEdge(nx * 1000 + ny, 100200, 1);
		printf("add    from: %d    to: %d \n", nx * 1000 + ny, 100200);*/
	}
	for (int i = 0; i < 4; i++)
	{
		int xx = nx + x[i], yy = ny + y[i];
		if (xx >= 0 && xx < n&&yy >= 0 && yy < m)
		{
			if (vis[xx][yy] == vis[nx][ny] - 1)
			{
				Pre_DFS(xx, yy, id);
			}
		}
	}
	vis[nx][ny] = 0;
}
bool Pre_BFS(int id)
{
	memset(vis, 0, sizeof(vis));
	int ex = need[id + 1].x, ey = need[id + 1].y;
	queue<Node>q;
	Node start; start.x = need[id].x, start.y = need[id].y;
	vis[start.x][start.y] = 1;
	q.push(start);
	while (!q.empty())
	{
		Node t = q.front();
		q.pop();
		if (t.x == ex&&t.y == ey)
		{
			Pre_DFS(t.x, t.y, id);
			return true;
		}
		for (int i = 0; i < 4; i++)
		{
			int xx = t.x + x[i], yy = t.y + y[i];
			if (xx >= 0 && xx < n&&yy >= 0 && yy < m&&mmp[xx][yy] != '#')
			{
				if (vis[xx][yy] == 0)
				{
					vis[xx][yy] = vis[t.x][t.y] + 1;
					Node next;
					next.x = xx, next.y = yy;
					q.push(next);
				}
			}
		}
	}
	return false;
}
void read()
{
	memset(need, -1, sizeof(need));
	neednum = 0;
	for (int i = 0; i < n; i++)
	{
		scanf("%s", mmp[i]);
		for (int j = 0; j < m; j++)
		{
			if (mmp[i][j] >= 'A'&&mmp[i][j] <= 'Z')
			{
				int id = mmp[i][j] - 'A';
				need[id].x = i, need[id].y = j;
				neednum++;
			}
			else if (mmp[i][j] >= 'a'&&mmp[i][j] <= 'z')
			{
				int id = mmp[i][j] - 'a' + 26;
				need[id].x = i, need[id].y = j;
				neednum++;
			}
		}
	}
}
void solve()
{
	read();
	bool flag = false;
	for (int i = 0; i < neednum; i++)
	{
		if (need[i].x == -1)
		{
			flag = true;
			break;
		}
	}
	if (flag || neednum<2)
	{
		printf("-1\n");
		return;
	}
	uN = neednum;
	for (int i = 0; i < uN - 1; i++)
	{
		vec[i].clear();
		//printf("add    from: %d    to: %d \n", 0, 100000 + i + 1);
		if (!Pre_BFS(i))
		{
			printf("-1\n");
			return;
		}
	}
	printf("%d\n", Match());
	return;
}
int main()
{
	while (scanf("%d%d", &n, &m) != EOF)
	{
		
		solve();
	}
	getchar();
	getchar();
}

五、反思

    

 对于DFS的回溯没有清空vis,导致超时,这是严重的错误,对于重合的最短路上的搜索若不清空vis,复杂度爆表要牢记。

Treasure Hunting

02-20

问题描述 :nnZstu_yhr is a very curious person who fell in love with math when he was in elementary school phase. When he entered the middle school, he learned Multiplication and Power Multiplication. yhr is so ambitious that he not only dreams to be a mathematician but also dreams to be richer than Bill Gates.nOne day, he is suddenly encountered with a crazy thought that is to hunt treasure to make one of his dreams a reality. Since yhr is such a strong-willed person that he will never give up as long as his goal has not been achieved. After going through 9*9 challenges, as a reward of god for that hard, he finally discovers an antique hole which is very likely to have a good number of treasures in it. However, as every novel writes, he can never get the treasures so easily. He has to open a coded door at first. He finds that there are 2*N numbers on the door. He speculates that they must be able to generate the password. Disappointedly, there isn’t any clue left for him. He has no better way but to YY. Firstly, he divides these 2*N number into N piles equally. The first pile is composed of a1,b1 and the second pile is composed of a2,b2…certainly, the i-th pile is composed of ai,bi…After completing this task, he calculates a1^b1*a2^b2*a3^b3…*an^bn and gets its result M. He takes M as the password to open the door. What’s a pity, he fails. Then he starts to YY again. Maybe the right password is the minimum number x which satisfies the equation x!%M=0. So he wants to have a try. But he doesn’t know how to get the number so that he has to turn to you for help. Can you help him?n输入:nnIn the first line is an integer T (1<=T<=50) indicating the number of test cases.nEach test case begins with an integer n (1<=n<=100), then followed n lines. Each line contains two numbers ai and bi (1 <= ai <= 100, 1<=bi<=10000000000000)n输出:nnIn the first line is an integer T (1<=T<=50) indicating the number of test cases.nEach test case begins with an integer n (1<=n<=100), then followed n lines. Each line contains two numbers ai and bi (1 <= ai <= 100, 1<=bi<=10000000000000)n样例输入:nn1n2n3 2n4 1n样例输出:nn6

The Treasure

05-04

We have arrived at the age of the Internet. Many software applications have transformed from stand-alone to online applications. Computer games are following this trend as well. Online games are becoming more and more popular, not only because they are more intelligent, but also because they can bring great profits. "The computer game industry is developing rapidly in China. Online game revenues amounted to 1.3 billion Yuan last year and are expected to reach 6.7 billion Yuan by 2007." reported by China Daily in 2004.nnHowever, good games originate from good programmers. We take for example that there is a RPG (Role Playing Game) and your boss asks you to implement some tasks. For simplicity's sake, we assume there are two kinds of roles in this game: one is player and the other is monster. You should help the player to achieve the goal: reach the place where treasure is positioned as early as possible and get the treasure.nnThe map of the game is a matrix of N * M identical cells. Some cells are passable blocks, and others are non-passable rocks. At any time, there is at most one role occupying a block. At the beginning, the time is set to 0, and the player is at a certain block. He then moves towards the treasure. At each turn, we have some rules:nnThe player can stay in the same block during the next one-second time duration, or he can walk or run towards the east, south, west, north, northeast, northwest, southeast, and southwest.nnnWith walking, the player can arrive at the corresponding passable blocks around him (See Fig.1). Each move takes 1 second.nWith running, the player can arrive at the corresponding passable blocks 2 cells away from him (See Fig.2). Each run takes 1 second. As demonstrated in Fig.3, if a neighbor cell is not passable, the player cannot run in that direction. For example, if cell 2 is a rock, running from 1 to 3 is impossible.nThe monsters are classified into aggressive and non-aggressive. If a monster occupies a cell, the player cannot move into that cell or run through that cell. In addition, the player cannot move into the cells surrounding an aggressive monster, because it will attack the player near it. For example, in Fig.4, if there is an aggressive monster in 5, then the cell 1, 2, 3, 4, 6, 7, 8 and 9 are in its attacking region, so the player cannot stay in or pass through these cells.nMonsters change their positions each turn. Each monster appears by its position sequence iteratively. That's to say, given the position sequence of monster i: (x1, y1), (x2, y2), ..., (xs, ys), its initial position is (x1, y1) at time 0, then it appears in (x2, y2) at time 1, and so on. When monster i arrives at (xs, ys) at time s-1, it will arrive in (x1, y1) at time s, and start to repeat.nAt the start of each turn, all the monsters change their positions first (the way of changing is given above). If a monster appears in the player's cell, or if an aggressive monster appears near the player to put him in its attacking region, the player will die, and the goal cannot be achieved. After all the monsters change their positions, the player makes a move or stays in the same cell. In his move, the moving path should not be occupied by any rocks or monsters or in the attacking region of any aggressive monsters. When counting the total time, we can neglect the time between monsters' position change and the player's move. Given the map of the game, the player's starting position, the treasure position and all the monsters' positions in every second, your task is to write a program to find the minimum time that the player gets the treasure.nInputnnThe input consists of several test cases. The first line of each case contains two integers N and M (1 <= N, M <= 100), where N is the height of the map and M is the width of the map. This is followed by N lines each containing M characters representing the map. A '#' represents a rock, a '.' is a free block, 'p' is the starting position of the player, 't' is the position of the treasure, 'n' is the initial position of a non-aggressive monster, and an 'a' stands for the initial position of an aggressive monster.nnThe cell (i, j) is the j-th cell on the i-th row counting from left to right. The rows are counted from 1 to N starting from the first line of the matrix. We can number all the monsters as 1, 2, 3�� according to their initial position, sorting first by row, then by column. The (n+2)-th line contains an integer p (0 <= p <= 100), which is the total number of monsters (i.e. the total number of 'n's and 'a's in the matrix). It is followed by p lines each specifying a monster's position sequence in the following format: the i-th (1 <= i <= p) line corresponds to monster i, which begins with an integer s (1 <= s <= 100), meaning the length of position sequence. Then s pairs of integers x1, y1, x2, y2, ��, xs, ys are followed, separated by blanks. Each pair is a free block in the map, (i.e. a monster never goes to a rock cell).nnIt is assured that none of the aggressive monsters' initial position is around the player. Two consecutive cases are separated by a blank line. The input is terminated by a line containing a pair of zeros.nnOutputnnFor each test case, output the minimum total time required for the player to get the treasure, in seconds. If it's not possible to get the treasure, or the minimum required time is greater than 100 seconds, please print a line just containing the string "impossible". Two consecutive cases should be separated by a blank line.nnSample Inputnn7 8n#.#####.n#.t#..p.n#..#....n..#a.#.#n#...##.nn.#......n........n2n2 4 4 5 4n3 5 8 6 8 5 7nn3 3np#.n##.nt..n0nn2 2n#tnp#n0nn0 0nnSample Outputnn8nnimpossiblenn1

Planet Hunting

12-27

DescriptionnnIn a fictitious solar system consisting of star S, a planet P, and its moon M, planet P orbits in a perfect circle around star S with a revolution period of exactly T Earth days, and moon M orbits in a perfect circle around planet P with an unknown revolution period. Given the position of moon M relative to star S at three different time points, your goal is to compute the distance of planet P from star S.nnTo do this, consider a two-dimensional Cartesian coordinate system with its origin centered at star S. You may assume that P’s counterclockwise orbit around S and M’s counterclockwise orbit around P both lie completely within the x – y coordinate plane. Let (x1, y1) denote the position of the moon M on the first observation, let (x2, y2) denote its position k1 Earth days later, and let (x3, y3) denote its position k2 Earth days after the second observation.nnInputnnThe input test file will contain multiple test cases. Each test case consists of two lines. The first line contains the integers T, k1, and k2, where 1 ≤ T, k1, k2 ≤ 1000. The second line contains six floating-point values x1, y1, x2, y2, x3, and y3. Input points have been selected so as to guarantee a unique solution; the final distance from planet P to star S will always be within 0.1 of the nearest integer. The end-of-file is denoted with a single line containing “0 0 0”.nnOutputnnFor each input case, the program should print the distance from planet P to star S, rounded to the nearest integer.nnSample Inputnn360 90 90n5.0 1.0 0.0 6.0 -5.0 1.0n0 0 0nSample Outputnn5

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭