• P3916 图的遍历 题解


    CSDN同步

    原题链接

    简要题意:

    求从每个点开始,可以到达的编号最大的点。

    我们只要发现一条性质,这题就变得挺简单了。

    你想,如果从每个点开始走,分别遍历,肯定是不科学的。

    因为是有向图,所以当前点 (x) 能到达的最大编号 (y),我们反向建图,(y) 一定也能走到 (x).而且,所以能走到 (y) 的点,反向建图之后,(y) 都能走到它们;如果不能走到 (y) 的点,反向建图后,(y) 也不能走到它们。

    所以,我们反向建图,从大到小遍历即可。

    时间复杂度:(O(n)).

    实际得分:(100pts).

    #pragma GCC optimize(2)
    #include<bits/stdc++.h>
    using namespace std;
    
    const int N=1e5+1;
    
    inline int read(){char ch=getchar();int f=1;while(ch<'0' || ch>'9') {if(ch=='-') f=-f; ch=getchar();}
    	int x=0;while(ch>='0' && ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x*f;}
    
    int n,m; int h[N]; //每个点的答案
    vector<int>G[N];
    
    inline void dfs(int dep,int top) {
    	if(h[dep]) return;
    	h[dep]=top; //记录答案的同时做哈希,因为先遍历到的答案肯定比后遍历的答案优
    	for(int i=0;i<G[dep].size();i++)
    		dfs(G[dep][i],top);
    }
    
    int main(){
    	n=read(),m=read(); while(m--) {
    		int x=read(),y=read();
    		G[y].push_back(x);
    	} for(int i=n;i>=1;i--)
    		if(!h[i]) dfs(i,i);
    	for(int i=1;i<=n;i++) printf("%d ",h[i]);	
    	return 0;
    }
    
    
  • 相关阅读:
    android 之短信发送
    android 系统之ContentProvider
    android 开发电话拔号
    android 开发笔记
    android 常用权限备份
    在IE中使用Firebug
    常用的公式语言
    ASP.NET程序访问MS SQL的方法
    [News]将有新的代码生成工具集成在designer 8.5.1中
    JS对Lotus域的操作
  • 原文地址:https://www.cnblogs.com/bifanwen/p/12565806.html
Copyright © 2020-2023  润新知