天梯赛 L3-011直捣黄龙
题目
本题是一部战争大片 —— 你需要从己方大本营出发,一路攻城略地杀到敌方大本营。首先时间就是生命,所以你必须选择合适的路径,以最快的速度占领敌方大本营。当这样的路径不唯一时,要求选择可以沿途解放最多城镇的路径。若这样的路径也不唯一,则选择可以有效杀伤最多敌军的路径。
输入格式:
输入第一行给出 2 个正整数 N(2 ≤ N ≤ 200,城镇总数)和 K(城镇间道路条数),以及己方大本营和敌方大本营的代号。随后 N-1 行,每行给出除了己方大本营外的一个城镇的代号和驻守的敌军数量,其间以空格分隔。再后面有 K 行,每行按格式城镇1 城镇2 距离给出两个城镇之间道路的长度。这里设每个城镇(包括双方大本营)的代号是由 3 个大写英文字母组成的字符串。
输出格式:
按照题目要求找到最合适的进攻路径(题目保证速度最快、解放最多、杀伤最强的路径是唯一的),并在第一行按照格式己方大本营->城镇1->...->敌方大本营输出。第二行顺序输出最快进攻路径的条数、最短进攻距离、歼敌总数,其间以 1 个空格分隔,行首尾不得有多余空格。
输入样例
DBY 100
PTA 20
PDS 90
PMS 40
TAP 50
ATP 200
LNN 80
LAO 30
LON 70
PAT PTA 10
PAT PMS 10
PAT ATP 20
PAT LNN 10
LNN LAO 10
LAO LON 10
LON DBY 10
PMS TAP 10
TAP DBY 10
DBY PDS 10
PDS PTA 10
DBY ATP 10
输出样例
PAT->PTA->PDS->DBY
3 30 210
题解
因为城市没有数字编号,只有string编号,所以这里使用unordered_map<string, othertype>来代替数组结构。
这里是求所有可能的最短路径,所以使用dijkstra算法的变式就可以了。
最后,根据dijkstra求完的所有最短路unordered_map<string,vector>pre,进行按题目要求的,解放数量,杀敌人数进行筛选即可(使用dfs遍历一下路径就可以了)
个人代码
using namespace std;
unordered_map<string, int> citys;
unordered_map<string, vector<pair<string, int>>> graph;
int N, K;
string sta, en;
const int inf = 0xfffffff;
const int MAXN = 210;
unordered_map<string, vector<string>>pre;
unordered_map<string, int>dis;
void dijkstra() {
priority_queue<pair<int, string>, vector<pair<int,string>>, greater<>> pq;
for (auto [s, cnt]: citys) {
dis.insert({s, inf});
}
dis.insert({sta, 0});
pq.push({0, sta});
while (pq.size()) {
int dist = pq.top().first;
string u = pq.top().second;
pq.pop();
if (dist>dis[u]) continue;
for (auto [v, w]: graph[u]) {
if (dis[v]>dis[u]+w) {
dis[v] = dis[u]+w;
pre[v]={u};
pq.push({dis[v], v});
}
else if (dis[v]==dis[u]+w) {
pre[v].push_back(u);
}
}
}
}
vector<string> result;
int max_cnt;
int max_amount;
int pos_roads;
void dfs(vector<string> &st, string nd, int cnt, int amount) {
st.push_back(nd);
if (pre[nd].empty()) {
pos_roads++;
if (cnt>max_cnt) {
max_cnt= cnt;
max_amount = amount;
result = st;
}
else if (cnt==max_cnt && amount>max_amount) {
max_amount = amount;
result = st;
}
st.pop_back();
return;
}
for (auto &a: pre[nd]) {
dfs(st, a, cnt+1, amount+citys[a]);
}
st.pop_back();
}
int main() {
cin>>N>>K;
cin>>sta>>en;
for (int i = 0; i <N-1; i++) {
string s;
int cnt;
cin>>s>>cnt;
citys[s] = cnt;
}
for (int i = 0; i<K; i++) {
string u, v;
int dis;
cin>>u>>v>>dis;
graph[u].push_back({v, dis});
graph[v].push_back({u, dis});
}
dijkstra();
vector<string> st;
dfs(st, en, 1, citys[en]);
for (int i = result.size()-1; i>=0; i--) {
if (i!=result.size()-1) printf("->");
cout << result[i];
}
cout << endl;
printf("%d %d %d\n", pos_roads, dis[en], max_amount);
}