7-11 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
ac:代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 505;
int map[maxn][maxn],dis[maxn];//map有向图dis距离
int in[maxn];//记录入度
int n,m;
int toposort()
{
queue<int>que;
memset(dis,0,sizeof(dis));
int cnt = 0;
for(int i = 0;i<n;i++){//选取入度为零的点,入队列
if(in[i]==0){
que.push(i);
}
}
while(!que.empty()){
int v = que.front();//取对顶
cnt++;
que.pop();
for(int i = 0;i<n;i++){
if(map[v][i]!=-1){//如果这条边存在,则更新长度
dis[i] = max(dis[i],map[v][i] + dis[v]);
if(--in[i]==0) que.push(i);
}
}
}
if(cnt==n) return 0;
else return 1;
}
int main()
{
memset(dis,0,sizeof(dis));
memset(in,0,sizeof(in));
memset(map,-1,sizeof(map));
cin>>n>>m;
int from,to,cost;
for(int i = 0;i<m;i++)
{
scanf("%d %d %d",&from,&to,&cost);
map[from][to] = cost;//有向图的赋值
in[to]++;
}
int ans = toposort();
if(ans) printf("Impossible\n");
else{
int max1 = -1;
for(int i = 0;i<n;i++){
if(max1<dis[i]){
max1 = dis[i];
}
}
printf("%d",max1);
}
return 0;
}
现在我来解释一下入度,如上图(手绘图),没有箭头指向1因此1的入度为零,同理3的入度也为零,2的入度为1,4的入度为2.