• [CF999E]Reachability from the Capital


    题目大意:有一个$n$个点$m$条边的有向图,起点$S$,要求你添加最少的边使得$S$可以到达所有点

    题解:缩点,答案就是没有入边的强连通分量个数,注意,如果起点$S$所在的强连通块没有入边则不计入答案

    卡点:

    C++ Code:

    #include <cstdio>
    #define maxn 5010
    #define maxm 5010
    int head[maxn], cnt;
    struct Edge {
    	int from, to, nxt;
    } e[maxm];
    inline void add(int a, int b) {
    	e[++cnt] = (Edge) {a, b, head[a]}; head[a] = cnt;
    }
    
    int DFN[maxn], low[maxn], idx;
    int S[maxn], top, res[maxn], CNT;
    bool ins[maxn];
    inline int min(int a, int b) {return a < b ? a : b;}
    void tarjan(int u) {
    	DFN[u] = low[u] = ++idx;
    	ins[S[++top] = u] = true;
    	int v;
    	for (int i = head[u]; i; i = e[i].nxt) {
    		int v = e[i].to;
    		if (!DFN[v]) {
    			tarjan(v);
    			low[u] = min(low[u], low[v]);
    		} else if (ins[v]) low[u] = min(low[u], DFN[v]);
    	}
    	if (DFN[u] == low[u]) {
    		CNT++;
    		do {
    			ins[v = S[top--]] = false;
    			res[v] = CNT;
    		} while (u != v);
    	}
    }
    int n, m, s;
    int ind[maxn];
    int main() {
    	scanf("%d%d%d", &n, &m, &s);
    	for (int i = 0, a, b; i < m; i++) {
    		scanf("%d%d", &a, &b);
    		add(a, b);
    	}
    	for (int i = 1; i <= n; i++) if (!DFN[i]) tarjan(i);
    	for (int i = 1; i <= cnt; i++) {
    		int u = res[e[i].from], v = res[e[i].to];
    		if (u != v) ind[v]++;
    	}
    	int ans = 0;
    	for (int i = 1; i <= CNT; i++) if (!ind[i]) ans++;
    	printf("%d
    ", ans - (!ind[res[s]]));
    	return 0;
    }
    

      

  • 相关阅读:
    SpringBoot之Banner介绍
    SpringBoot事件监听机制
    SpringBoot 启动流程图
    ApplicationContextInitializer的理解和使用
    SpringFactoriesLoader解析
    计时器之StopWatch
    ftp上下载文件
    打印两个函数的返回值
    关闭所有已打开的文件和关闭应用
    TypeError: include() got an unexpected keyword argument 'app_name'
  • 原文地址:https://www.cnblogs.com/Memory-of-winter/p/9744793.html
Copyright © 2020-2023  润新知