用c语言实现本题
时间: 2023-10-23 07:09:41 浏览: 85
使用C语言实现
好的,以下是C语言代码实现,使用了Dijkstra算法求解最短路径和记录沿途解放城镇数和歼伤敌军数的方法:
```c
#include <stdio.h>
#include <string.h>
#define N 210
#define INF 0x3f3f3f3f
int n, m, cnt;
int graph[N][N], dist[N], path[N], num[N], kill[N], vis[N];
char start[4], end[4], city[N][4];
int get_index(char str[]) {
for (int i = 1; i <= n; i++) {
if (strcmp(city[i], str) == 0)
return i;
}
return 0;
}
void dijkstra(int start) {
memset(vis, 0, sizeof(vis));
memset(dist, INF, sizeof(dist));
memset(num, 0, sizeof(num));
memset(kill, 0, sizeof(kill));
dist[start] = 0;
num[start] = 1;
kill[start] = graph[start][start];
for (int i = 1; i <= n; i++) {
int u = 0;
for (int j = 1; j <= n; j++) {
if (!vis[j] && (u == 0 || dist[j] < dist[u]))
u = j;
}
vis[u] = 1;
for (int v = 1; v <= n; v++) {
if (!vis[v] && graph[u][v] != INF) {
if (dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
num[v] = num[u] + 1;
kill[v] = kill[u] + graph[u][v];
path[v] = u;
} else if (dist[u] + graph[u][v] == dist[v]) {
if (num[u] + 1 > num[v]) {
num[v] = num[u] + 1;
kill[v] = kill[u] + graph[u][v];
path[v] = u;
} else if (num[u] + 1 == num[v]) {
if (kill[u] + graph[u][v] > kill[v]) {
kill[v] = kill[u] + graph[u][v];
path[v] = u;
}
}
}
}
}
}
}
void print_path(int end) {
if (end == 0)
return;
print_path(path[end]);
printf("->%s", city[end]);
}
int main() {
scanf("%d%d%s%s", &n, &m, start, end);
for (int i = 1; i < n; i++) {
char name[4];
int num;
scanf("%s%d", name, &num);
int index = get_index(name);
strcpy(city[index], name);
graph[1][index] = graph[index][1] = num;
}
for (int i = 0; i < m; i++) {
char name1[4], name2[4];
int len;
scanf("%s%s%d", name1, name2, &len);
int index1 = get_index(name1);
int index2 = get_index(name2);
graph[index1][index2] = graph[index2][index1] = len;
}
int start_index = get_index(start);
int end_index = get_index(end);
dijkstra(start_index);
printf("%s", start);
print_path(end_index);
printf("\n%d %d %d", num[end_index], dist[end_index], kill[end_index]);
return 0;
}
```
注意:在使用Dijkstra算法时,需要对每个节点初始化。在本题中,需要同时记录沿途解放城镇数和歼伤敌军数,所以需要额外开辟数组分别记录。同时需要注意在输出路径时,先输出起点,再倒序输出路径上的节点。
阅读全文