Input is a rectangular grid; each grid square either has the Enterprise or some class of a Klingon warship. Associated with each class of Klingon warship is a time that it takes for the Enterprise to defeat that Klingon. To escape, the Enterprise must defeat each Klingon on some path to the perimeter. Squares are connected by their edges, not by corners (thus, four neighbors).
InputThe first line will contain T, the number of cases; 2 ≤ T ≤ 100. Each case will start with line containing three numbers k, w, and h. The value for k is the number of different Klingon classes and will be between 1 and 25, inclusive. The value for w is the width of the grid and will be between 1 and 1000, inclusive. The value for h is the height of the grid and will be between 1 and 1000, inclusive.
Following that will be k lines. Each will consist of a capital letter used to label the class of Klingon ships followed by the duration required to defeat that class of Klingon. The label will not be "E". The duration is in minutes and will be between 0 and 100,000, inclusive. Each label will be distinct.
Following that will be h lines. Each will consist of w capital letters (with no spaces between them). There will be exactly one "E" across all h lines, denoting the location of the Enterprise; all other capital letters will be one of the k labels given above, denoting the class of Klingon warship in the square.
Your output should be a single integer value indicating the time required for the Enterprise to escape.
2 6 3 3 A 1 B 2 C 3 D 4 F 5 G 6 ABC FEC DBG 2 6 3 A 100 B 1000 BBBBBB AAAAEB BBBBBB
2 400
分析题意可知,这是一道变形的最短路径问题,通过寻找总作战次数最少的路线来求出最终结果
通过广度搜索加上贪心算法的思维来求出答案。其中为了优化搜索时间,使用了优先队列的贪心思维,而不使用优先队列的话,可能面临超时的问题,且会大大增加算法的复杂度。
#include<cstdio>
#include<queue>
#include<vector>
#include<iostream>
#include<cstring>
#include<map>
using namespace std;
struct po{
int x,y,time;
};
bool operator<(po a,po b)
{
return a.time>b.time;
}
char ch[1005][1005];int flag[1005][1005];
int dx[4]{0,0,-1,1};
int dy[4]{1,-1,0,0};
int letter[27];
int main()
{
int t;cin>>t;
while(t--)
{
int k,w,h;cin>>k>>w>>h;
po sta;///map<char,int>s;
for(int i=0;i<k;i++){int x;char a;cin>>a>>x;letter[a-'A']=x;}
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
cin>>ch[i][j];
if(ch[i][j]=='E'){sta.x=j,sta.y=i,sta.time=0;}
}
}
priority_queue<po>it;
memset(flag,0,sizeof(flag));
flag[sta.y][sta.x]=1;
it.push(sta);int sum=-1;
while(!it.empty())
{
po to;to=it.top();it.pop();
for(int i=0;i<4;i++)
{
int x=to.x+dx[i];
int y=to.y+dy[i];
if(x<0||x>=w||y<0||y>=h)
{
sum=to.time;break;
}
if(flag[y][x])continue;
flag[y][x]=1;//之前这里没标记,结果交了好几遍都超内存了;
po next;next.x=x,next.y=y,next.time=to.time+letter[ch[y][x]-'A'];
it.push(next);
}
if(sum>-1)break;
}
cout<<sum<<endl;
}
}
本文探讨了一个变形的最短路径问题,通过广度优先搜索结合贪心算法来寻找使宇宙飞船 Enterprise 能够尽快从 Klingon 战舰群中逃脱的最佳路径。文章提供了一段 C++ 代码实现,利用优先队列优化搜索过程,确保在限定时间内找到最优解。
911

被折叠的 条评论
为什么被折叠?



