关键路径寻找(C语言)

关键路径寻找
对于给定的一个工程施工图,该图以边为单位从键盘输入,编写能够找出该图的关键路径的程序。
代码如下:

#include <stdio.h>
#include <stdlib.h>

struct TU
{
    int index;
    int dut;
    int vex;
    char act[5];
    struct TU *link;
};
struct TU s[100];
struct TU *p;
struct TU *creat()
{
    int i =0;
    int a,d,v,u;
    struct TU *p;
    printf("建立图的邻接表\n");
    while(1)
    {

        printf("输入结点,结点的入度(u,a),(u == 0退出)\n");
        scanf("%d,%d",&u,&a);
        if(u == 0)
            break;
        else
        {
            i = i+1;
            s[i].index = a;
            s[i].vex = u;
            s[i].link = NULL;
            printf("输入与此结点有关的边,结点,权值(act v,d),(任一值为0退出)\n");
            while(1)
            {
                p = (struct TU *)malloc(sizeof(struct TU));
                scanf("%s%d,%d",&p->act,&v,&d);
                if(d == 0 || v ==0)
                    break;
                else
                {
                    p->dut = d;
                    p->vex = v;
                    p->link = s[i].link;
                    s[i].link = p;
                }
            }
        }
    }
    s[0].vex = i;
    return 0;
};
void topsort()
{

    int vltop = 0,vetop = 0;
    int i,b=1;
    int m = 0,n,j,k,endnode;
    n = s[0].vex;/*获得结点数*/
    int Ve[n];
    int Vl[n];
    for(int i = 1;i<=n;i++)
    {
        if(s[i].index == 0)
        {
            s[i].index = vetop;
            vetop = i;
        }
        Ve[i] = 0;
    }
/*求各事件的最早发生时间*/
    while(vetop !=0)
    {
        j = vetop;
        m = m+1;
        vetop = s[vetop].index;
        s[j].index = vltop;
        vltop = j;
        p = s[j].link;
        while(p)
        {
            k = p->vex;
            s[k].index = s[k].index -1;
            if(s[k].index == 0)
            {
                s[k].index = vetop;
                vetop = k;
            }
            if(Ve[k]<Ve[j]+p->dut)
                Ve[k] = Ve[j]+p->dut;
            p = p->link;
        }
    }
    if(m<n)
    {
        printf("图有环\n");
        return;
    }
    endnode = vltop;
    for(int i = 1;i<=endnode;i++)
       Vl[i] = Ve[endnode];
    /*求各事件的最晚发生时间*/
    while(vltop != 0)
    {
        j = vltop;
        vltop = s[vltop].index;
        p = s[j].link;
        while(p)
        {
            k = p->vex;
            if(Vl[j]>Vl[k]-(p->dut))
                Vl[j] = Vl[k]-p->dut;
            p = p->link;
        }
    }
    for(i = 1;i<=n;i++)
        printf("Ve(%d)= %d, Vl(%d)=%d\n",i,Ve[i],i,Vl[i]);
    printf("关键路径\n");
    for(b=1;b<=s[0].vex;b++)
    {
        if(Ve[b]==Vl[b])
        {
            printf("V(%d)->",b);
        }
    }
    printf("\n");

}
int main()
{
    struct TU *p;
    creat();
    printf("邻接表\n");
    for(int i = 1;i<=s[0].vex;i++)
    {
        printf("s[%d]=%d/ ",i,s[i].vex);
        p = s[i].link;
        while(p)
        {
            printf("-%s-[%d(%d)]",p->act,p->vex,p->dut);
            p = p->link;
        }
        printf("\n");
    }
    topsort();

    return 0;
}

你可能感兴趣的:(笔记)