运输问题表上作业法c语言
时间: 2023-10-26 07:02:19 浏览: 22
运输问题可以使用表上作业法来解决,以下是用C语言实现表上作业法的示例代码:
```c
#include <stdio.h>
#define MAX 100
void northWestCorner(int m, int n, int supply[MAX], int demand[MAX], int cost[MAX][MAX]);
void printSolution(int m, int n, int allocation[MAX][MAX], int cost[MAX][MAX]);
int main() {
int m, n, i, j;
int supply[MAX], demand[MAX], cost[MAX][MAX];
printf("Enter the number of sources (m): ");
scanf("%d", &m);
printf("Enter the number of destinations (n): ");
scanf("%d", &n);
printf("Enter the supply values:\n");
for (i = 1; i <= m; i++) {
scanf("%d", &supply[i]);
}
printf("Enter the demand values:\n");
for (j = 1; j <= n; j++) {
scanf("%d", &demand[j]);
}
printf("Enter the cost matrix:\n");
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
}
}
northWestCorner(m, n, supply, demand, cost);
return 0;
}
void northWestCorner(int m, int n, int supply[MAX], int demand[MAX], int cost[MAX][MAX]) {
int i, j, allocation[MAX][MAX] = {0};
int totalCost = 0;
i = 1;
j = 1;
while (i <= m && j <= n) {
if (supply[i] < demand[j]) {
allocation[i][j] = supply[i];
demand[j] -= supply[i];
totalCost += allocation[i][j] * cost[i][j];
i++;
} else {
allocation[i][j] = demand[j];
supply[i] -= demand[j];
totalCost += allocation[i][j] * cost[i][j];
j++;
}
}
printSolution(m, n, allocation, cost);
printf("Total Cost: %d\n", totalCost);
}
void printSolution(int m, int n, int allocation[MAX][MAX], int cost[MAX][MAX]) {
int i, j;
printf("Allocation Matrix:\n");
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
printf("%d\t", allocation[i][j]);
}
printf("\n");
}
printf("Cost Matrix:\n");
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
printf("%d\t", cost[i][j]);
}
printf("\n");
}
}
```
在这段代码中,我们首先输入了运输问题的基本数据,即源点数、汇点数、供应量、需求量和成本矩阵。然后使用表上作业法计算出最优解,并打印出分配矩阵和成本矩阵以及总成本。
这里使用了两个函数,`northWestCorner()` 和 `printSolution()`。`northWestCorner()` 函数实现了表上作业法,`printSolution()` 函数用于打印出分配矩阵和成本矩阵。
阅读全文