#include<stdio.h>
#include<string.h>
#define MAX 100
#define infinite 100
typedef struct graph {
int vn;
int cost[MAX][MAX];
char vertex[MAX];
char topo[MAX];
int indge[MAX];
int ve[MAX];
int vl[MAX];
} GH;
int getindex(GH * gh,char target);
void cpa(GH * gh,int ve[MAX],int vl[MAX]);
void toposort(GH * gh,int visited[MAX]);
void getindge(GH * gh);
int main() {
int ve[MAX] = {0},vl[MAX] = {0};
GH grah;
GH * gh = &grah;
int i = 0,j = 0;
int visited[MAX] = {0};
char temp = '\0';
scanf("%d",&gh->vn);
temp = getchar();
for(i = 0; i < gh->vn; i++) {
scanf("%c",&gh->vertex[i]);
temp = getchar();
}
for(i = 0; i < gh->vn; i++) {
for(j = 0; j < gh->vn; j++) {
scanf("%d",&gh->cost[i][j]);
}
}
for(i = 0; i < gh->vn; i++) {
gh->topo[i] = '\0';
vl[i] = MAX;
gh->indge[i] = 0;
}
getindge(gh);
toposort(gh,visited);
cpa(gh,ve,vl);
return 0;
}
int getindex(GH * gh,char target) {
int i = 0;
for(i = 0; i < gh->vn; i++) {
if(gh->vertex[i] == target) return i;
}
return -1;
}
void cpa(GH * gh,int ve[MAX],int vl[MAX]) {
int i = 0,j = 0,indi = 0,indj = 0;
for(i = 0; i < gh->vn; i++) {
for(j = i + 1; j < gh->vn; j++) {
indi = getindex(gh,gh->topo[i]);
indj = getindex(gh,gh->topo[j]);
if(ve[j] < ve[i] + gh->cost[indi][indj]&&gh->cost[indi][indj] != infinite)
ve[j] = ve[i] + gh->cost[indi][indj];
}
}
vl[gh->vn - 1] = ve[gh->vn - 1];
for(i = gh->vn - 1; i >= 0; i--) {
for(j = i - 1; j >= 0; j--) {
indi = getindex(gh,gh->topo[i]);
indj = getindex(gh,gh->topo[j]);
if(vl[j] >= vl[i] - gh->cost[indj][indi]&&gh->cost[indj][indi] != infinite)
vl[j] = vl[i] - gh->cost[indj][indi];
}
}
for(i = 0; i < gh->vn; i++) {
if(ve[i] == vl[i]) printf("%c ",gh->topo[i]);
}
}
void toposort(GH * gh,int visited[MAX]) {
int i = 0,this = 0,flag = 0;
for(i = 0; i < gh->vn; i++) {
if(gh->indge[i] == 0&&visited[i] == 0) {
this = i;
visited[i] = 1;
break;
}
}
for(i = 0; i < gh->vn; i++) {
if(gh->cost[this][i] > 0&&gh->cost[this][i] != infinite) {
gh->indge[i]--;
flag = 1;
}
}
gh->topo[strlen(gh->topo)] = gh->vertex[this];
if(flag == 1) toposort(gh,visited);
}
void getindge(GH * gh) {
int i = 0,j = 0;
for(i = 0; i < gh->vn ; i++) {
for(j = 0; j < gh->vn; j++) {
if(gh->cost[j][i] > 0&&gh->cost[j][i] != infinite) {
gh->indge[i]++;
}
}
}
}
关键路径算法 ---- C语言
最新推荐文章于 2021-12-07 17:23:06 发布