关键路径算法 ---- C语言

#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]++;
		}
	}
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值