1 阿里—编程测验
题目
给出一个有向无环图,有向边“A -> B”的含义是:节点A依赖于节点B,并且每个节点给出一个附加消耗值Vi,i => [1, n],定义一条有向链条为”从入度为0的节点”沿着有向边一直到达一个”出度为0的节点”的所有边和节点的集合,有向链条上所有节点的消耗值的和为该有向链条的消耗值。
求:最大的有向链条的深度,所有有向链条对应消耗值的最大值。
输入样例:
5 4 // 表示有5个系统和 4个依赖关系
3 // 调用1号系统耗时 3 ms
2 // 调用2号系统耗时 2 ms
10 // 调用3号系统耗时 10 ms
5 // 调用4号系统耗时 5 ms
7 // 调用5号系统耗时 7 ms
1 2 // 2号系统依赖1号系统
1 3 // 3号系统依赖1号系统
2 5 // 5号系统依赖2号系统
4 5 // 5号系统依赖4号系统
输出样例:
3 13
思路:
遍历入度为0的节点 + 对每一个节点进行dfs
代码如下:
#include<stdio.h>
#define huha 10000
typedef struct{
int time;
int _v[huha];
int _v_c;
int _in;
}node;
int n, m;
node nn[huha];
int res_max = 0;
int res_time = 0;
void dfs(int i, int res1, int res2){
res2 += nn[i].time;
res1 ++;
if(nn[i]._v_c == 0){
if(res1 > res_max){
res_max = res1;
}
if(res2 > res_time){
res_time = res2;
}
}else{
int j;
for(j = 0; j < nn[i]._v_c; j ++){
dfs(nn[i]._v[j], res1, res2);
}
}
}
char hh[huha];
// 注意解决一下输入输出问题
int main(){
gets(hh);
//fflush(stdin);
sscanf(hh, "%d%d", &n, &m);
int i;
for(i = 1; i <= n; i ++){
gets(hh);
//fflush(stdin);
sscanf(hh, "%d", &nn[i].time);
nn[i]._v_c = 0;
nn[i]._in = 0;
}
int a, b;
for(i = 0; i < m; i ++){
gets(hh);
//fflush(stdin);
sscanf(hh, "%d%d", &a, &b);
nn[b]._v[nn[b]._v_c ++] = a;
nn[a]._in ++;
}
for(i = 1; i <= n; i ++){
if(nn[i]._in == 0){
dfs(i, 0, 0);
}
}
printf("%d %d\n", res_max, res_time);
return 0;
}