题目大意:给定一个 N 个点,M 条边的有向图,求每个点能够到达的节点的最大编号是多少。

题解:因为题中所给图不一定是一个 DAG,因此无法进行按照拓扑序来动态规划,需要另辟蹊径。由于求的是每个节点能够到达的最大编号,因此可以考虑反向建图,并依次从大到小枚举节点编号,将该节点能够到达的节点修改为当前节点的编号,算法正确性显然。

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10; inline int read(){
int x=0,f=1;char ch;
do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
return f*x;
} struct node{
int nxt,to;
}e[maxn];
int tot=1,head[maxn];
int n,m,dp[maxn];
inline void add_edge(int from,int to){
e[++tot]=node{head[from],to},head[from]=tot;
} void read_and_parse(){
n=read(),m=read();
for(int i=1,from,to;i<=m;i++){
from=read(),to=read();
add_edge(to,from);
}
} void bfs(int idx){
queue<int> q;
q.push(idx);
while(q.size()){
int u=q.front();q.pop();
dp[u]=idx;
for(int i=head[u];i;i=e[i].nxt)if(!dp[e[i].to])q.push(e[i].to);
}
} void solve(){
for(int i=n;i>=1;i--){
if(dp[i])continue;
bfs(i);
}
for(int i=1;i<=n;i++)printf("%d%c",dp[i],i==n?'\n':' ');
} int main(){
read_and_parse();
solve();
return 0;
}

最新文章

  1. js~~给网站图片添加水印~~~
  2. hdu 3709 数位dp
  3. MyBatis知多少(13)MyBatis如何解决数据库的常见问题
  4. [CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组
  5. HashSet HashTable HashMap的区别
  6. Android 系统属性
  7. SYNONYMS
  8. 自定义DTD(myeclipser的XML提示功能)
  9. libevent学习总结
  10. 准确率(Accuracy), 精确率(Precision), 召回率(Recall)和F1-Measure(对于二分类问题)
  11. 关于JDK和eclipse的安装和汉化
  12. Matrix-tree 定理的一些整理
  13. ModBus-RTU详解
  14. 使用php的curl爬去青果教务系统 课表(转)
  15. REST AND SOAP
  16. 一篇入门 -- Scala 反射
  17. python,中使用while...else 和 for...else 还有try...else,另外就是运用with关键字
  18. 662. Maximum Width of Binary Tree二叉树的最大宽度
  19. Maven 生成项目站点
  20. Unity3d官方测试插件学习-单元测试,集成测试

热门文章

  1. 20155202《网络对抗》Exp8 Web基础
  2. 20155320《网络对抗》Exp4 恶意代码分析
  3. 20155321 《网络攻防》 Exp8 Web基础
  4. WPF应用
  5. 蓝牙disable流程简述
  6. 基于tensorflow2.0 使用tf.keras实现Fashion MNIST
  7. NO.3:自学tensorflow之路------MNIST识别,神经网络拓展
  8. PAT甲题题解-1110. Complete Binary Tree (25)-(判断是否为完全二叉树)
  9. 第五次Scrum meeting
  10. 20135202闫佳歆--week3 跟踪分析Linux内核的启动过程--实验及总结