码迷,mamicode.com
首页 > 其他好文 > 详细

题解 P2002 消息扩散

时间:2019-10-04 16:50:02      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:names   也有   long   模版   stream   algorithm   pac   return   ring   

题解 P2002 消息扩散

题目链接

非常裸的一道缩点题,很显然每个强连通分量里给一个点消息就够了,缩完点以后很显然我们要讨论每一个点的入度。对于入度为零的点(没有其它点能给他消息),我们就必须给它一份消息,所以就变成了数入度为零的点。由于数据规模,所以我们不需要重新建图。

值得一提的是一个小细节。重边和自环。我一开始用map判重边结果t了一个点(也有可能是这个点有自环qaq),然后删了map特判判自环就直接过了,看来重边好像对这道题没什么影响??(大雾

代码:几乎是裸的模版题,好像比模版题还简单点

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
#include <vector>
#include <map>
#define N 100005
#define ll long long
using namespace std;

inline int read()
{
    int x = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); }
    while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}
vector < int > a[N];
stack < int > s;
map < pair < int, int >, int > mp;
int n, m, times, dfn[N], low[N], instc[N], vis[N], mtot, du[N], ans;
//vector存图可能会慢
void tarjan(int x)
{
    dfn[x] = low[x] = ++times;
    instc[x] = 1;
    s.push(x);
    for (int i = 0; i < a[x].size(); i++)
    {
        int u = a[x][i];
        if (!dfn[u])
        {
            tarjan(u);
            low[x] = min(low[x], low[u]);
        }
        else if (instc[u])
            low[x] = min(low[x], dfn[u]);
    }
    if (dfn[x] == low[x])
    {
        ++mtot;
        vis[x] = mtot;
        instc[x] = false;
        while (s.top() != x)
        {
            vis[s.top()] = mtot;
            instc[s.top()] = 0;
            s.pop();
        }
        s.pop();
    }
}

int main()
{
    n = read(), m = read();
    for (int i = 1; i <= m; i++) { int a1 = read(), a2 = read(); if (a1 != a2) a[a1].push_back(a2); }
    for (int i = 1; i <= n; i++)
        if (!dfn[i]) tarjan(i);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j < a[i].size(); j++)
        {
            int u = a[i][j];
            if (vis[u] != vis[i])
            {
                du[vis[u]]++; //更新入度 (不在乎是否重复)
            }
        }
    }
    for (int i = 1; i <= mtot; i++)
        if (du[i] == 0) ans++; //统计入度累加答案
    cout << ans << endl;
    return 0;
}

最后推荐几个相似题目,做tarjan必刷:

P1262 间谍网络

P2341 [HAOI2006]受欢迎的牛|【模板】强连通分量

P3627 [APIO2009]抢掠计划

最后吐槽下为什么这么裸的tarjan都是蓝题,因为普及组不考么qaq

19.09.05

题解 P2002 消息扩散

标签:names   也有   long   模版   stream   algorithm   pac   return   ring   

原文地址:https://www.cnblogs.com/YuanqiQHFZ/p/11622349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!