7-12 How Long Does It Take (25分)

Given the relations of all the activities of a project, you are supposed to find the earliest completion time of the project.

Input Specification:

Each input file contains one test case. Each case starts with a line containing two positive integers N (≤100), the number of activity check points (hence it is assumed that the check points are numbered from 0 to N−1), and M, the number of activities. Then M lines follow, each gives the description of an activity. For the i-th activity, three non-negative numbers are given: S[i], E[i], and L[i], where S[i] is the index of the starting check point, E[i] of the ending check point, and L[i] the lasting time of the activity. The numbers in a line are separated by a space.

Output Specification:

For each test case, if the scheduling is possible, print in a line its earliest completion time; or simply output “Impossible”.

Sample Input 1:

9 12
0 1 6
0 2 4
0 3 5
1 4 1
2 4 1
3 5 2
5 4 0
4 6 9
4 7 7
5 7 4
6 8 2
7 8 4


Sample Output 1:

18


Sample Input 2:

4 5
0 1 1
0 2 2
2 1 3
1 3 4
3 2 5


Sample Output 2:

Impossible


源码：

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

#define INFINITY 99999999
#define MaxVertexNum 110 /* maximum number of vertices */
typedef int Vertex;      /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef int WeightType;

typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
int pen[MaxVertexNum]={0};
int result[MaxVertexNum]={0};
int stack[MaxVertexNum];
int top=-1;
int least[MaxVertexNum]={0};

{
MGraph G=(MGraph)malloc(sizeof(struct GNode));
G->Nv=N;
G->Ne=M;
int i,j;
for(i=0;i<G->Nv;i++)
{
for(j=0;j<G->Nv;j++)
{
G->G[i][j]=INFINITY;
if(i==j)
{
G->G[i][j]=0;
}
}
}
for(i=1;i<=G->Ne;i++)
{
int a,b,x,y;
scanf("%d%d%d",&a,&b,&x);
G->G[a][b]=x;
pen[b]++;
}

for(i=0;i<G->Nv;i++)
{
if(pen[i]==0)stack[++top]=i;
}
return G;
}
int topo(MGraph G)
{
int m=0;
while(top!=-1)
{
int t=stack[top--];
m++;
for(int i=0;i<G->Nv;i++)
{
if(G->G[t][i]!=INFINITY&&t!=i)
{
pen[i]--;
if(result[t]+G->G[t][i]>result[i])result[i]=result[t]+G->G[t][i];
if(pen[i]==0)stack[++top]=i;
}
}
}
if(m<G->Nv)return 0;
else {
int max=0;
for(int i=0;i<G->Nv;i++)
{
if(result[i]>=max)max=result[i];
}

return max;
}
}
int main()
{
int N,M;
scanf("%d%d",&N,&M);
int f=topo(G);

if(f)
printf("%d\n",f);
else
printf("Impossible\n");

return 0;
}


©️2019 CSDN 皮肤主题: 黑客帝国 设计师: 上身试试