当前位置: 首页 > article >正文

浙大数据结构:08-图8 How Long Does It Take

这道题算是较为简单的拓扑排序题,难度不大
机翻

1、条件准备

n,m为n个结点,m条边。
tim数组存到该结点完成的最早时间,会一点点更新
graph存有向边的时间
indegree数组存每个结点的入度

#include <iostream>
#include <vector>
#include<string.h>
using namespace std;
#define endl '\n'

int n,m;
int tim[105];
int graph[105][105];
int indegree[105];

2、主函数

初始化graph为-1,表示没有路径。
输入有向边的数据,存到graph数组中,更新入度
最后进行拓扑排序即可

int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin>>n>>m;
memset(graph,-1,sizeof(graph));
while(m--)
{
  int s,e,l;
  cin>>s>>e>>l;
  indegree[e]++;
  graph[s][e]=l;
}
tuopu();
  return 0;
}

3、tuopu函数

还是用数组模拟队列存储入度为0的结点。
先遍历一遍把入度为0的结点加入队列
遍历队列,取队头元素,看它到其它结点有没有路径,
有的话更新tim,可达结点的tim变为当前结点的完成时间和本身的较大值,–入度,如果为0就加入队列。
最后如果入队的元素不为结点数量输出Impossible
否则遍历一遍timm数组,输出最大值

void tuopu()
{
  int q[105];int hh=0,tt=-1;//数组模拟队列
  for(int i=0;i<n;i++)
  if(indegree[i]==0)q[++tt]=i;

  while(hh<=tt)
  {
    int cur=q[hh++];
    for(int i=0;i<n;i++)
    {
      if(graph[cur][i]<0)continue;
      tim[i]=max(tim[i],tim[cur]+graph[cur][i]);
      if(--indegree[i]==0)q[++tt]=i;
    }
  }
  int answer=0;
  if(tt!=n-1)
  {
    cout<<"Impossible";return ;
  }
  for(int i=0;i<n;i++)
   answer=max(answer,tim[i]);
   cout<<answer;
}

4、总结

这道题算是拓扑排序较易题,难度不大
完整代码如下

#include <iostream>
#include <vector>
#include<string.h>
using namespace std;
#define endl '\n'

int n,m;
int tim[105];
int graph[105][105];
int indegree[105];
void tuopu()
{
  int q[105];int hh=0,tt=-1;//数组模拟队列
  for(int i=0;i<n;i++)
  if(indegree[i]==0)q[++tt]=i;

  while(hh<=tt)
  {
    int cur=q[hh++];
    for(int i=0;i<n;i++)
    {
      if(graph[cur][i]<0)continue;
      tim[i]=max(tim[i],tim[cur]+graph[cur][i]);
      if(--indegree[i]==0)q[++tt]=i;
    }
  }
  int answer=0;
  if(tt!=n-1)
  {
    cout<<"Impossible";return ;
  }
  for(int i=0;i<n;i++)
   answer=max(answer,tim[i]);
   cout<<answer;
}
int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin>>n>>m;
memset(graph,-1,sizeof(graph));
while(m--)
{
  int s,e,l;
  cin>>s>>e>>l;
  indegree[e]++;
  graph[s][e]=l;
}
tuopu();
  return 0;
}


http://www.kler.cn/news/340996.html

相关文章:

  • P1903 [国家集训队] 数颜色 / 维护队列
  • 叉车毫米波雷达防撞技术,保护叉车作业安全
  • 图像分类-demo(Lenet),tensorflow和Alexnet
  • 深度学习基础—残差网络ResNets
  • springboot 整合 rabbitMQ(2)
  • 【SQL】深入了解 SQL 索引:数据库性能优化的利器
  • C#操作SqlServer数据库事务
  • BMS 硬件工程师面试题
  • 【unity进阶知识8】unity场景Scene的使用, 如何封装一个场景管理器
  • HeidiSQL 数据库密码如何恢复
  • [CTF夺旗赛] CTFshow Web13-14 详细过程保姆级教程~
  • 是否可以将缓存的 hashCode 方法添加到原始字符串?
  • 深度学习模型
  • LabelImag标注工具环境配置
  • 【Matlab案例】imageJ + matlab 实现物体轨迹追踪及路径彩色上色
  • 【数据分析】参数检验与非参数检验
  • C语言 | Leetcode C语言题解之第468题验证IP地址
  • 【python 简易入门应用教程】第一部分:Python 基础
  • 信息安全工程师(40)防火墙技术应用
  • Word 首行缩进 2 字符怎么设置?具体步骤演示