zoukankan      html  css  js  c++  java
  • 【BZOJ】1051 [HAOI2006]受欢迎的牛

    【题意】给定n个点m条边的有向图,求多少个点能被其它所有点到达。n<=10000,m<=50000。

    【算法】强联通分量(tarjan)

    【题解】如果有k个点能从除自己外的所有点到达(即k个答案点),那么这k个点一定在一个连通块中。

    tarjan缩点构建新图,那个所有答案点都被缩成了一个点。出度为0的点中包含的原图点个数即是答案。

    新图中,假设有一个点出度不为0而能被其他任意点到达,那么这个点连出去的边到达的点a应该与这个点属于同一个强连通分量,与此图已经没有强连通分量(tarjan过了)矛盾。

    假设有两个点出度为0,那么他们不能互相到达,都不能成为答案。

    因此,新图中若有且只有一个出度为0的点则输出这个强连通分量包含的点的个数,否则输出0。

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    const int maxn=10010,maxm=50010;
    struct edge{int u,v,from;}e[maxm],e1[maxm];
    int n,m,dfn[maxn],low[maxn],col[maxn],colnum[maxn],color,s[maxn],top,tot,mark,tot1,first[maxn],first1[maxn],ans[maxn],lack[maxn];
    void insert(int u,int v)
    {tot++;e[tot].u=u;e[tot].v=v;e[tot].from=first[u];first[u]=tot;}
    void insert1(int u,int v)
    {tot1++;e1[tot1].u=u;e1[tot1].v=v;e1[tot1].from=first1[u];first1[u]=tot1;ans[u]++;}
    void tarjan(int x)
    {
        dfn[x]=low[x]=++mark;
        s[++top]=x;lack[x]=top;
        for(int i=first[x];i;i=e[i].from)
         {
             int y=e[i].v;
             if(!dfn[y])
              {
                  tarjan(y);
                  low[x]=min(low[x],low[y]);
              }
             else if(lack[y])
              {
                  low[x]=min(low[x],dfn[y]);
              }
         }
        if(dfn[x]==low[x])
         {
             color++;
             for(int i=lack[x];i<=top;i++)col[s[i]]=color;
             colnum[color]=top-lack[x]+1;
             top=lack[x]-1;
         }
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=m;i++)
         {
             int u,v;
             scanf("%d%d",&u,&v);
             insert(u,v);
         }
        for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i);
        for(int i=1;i<=m;i++)
         if(col[e[i].u]!=col[e[i].v])insert1(col[e[i].u],col[e[i].v]);
        int ansnum=0,ansi;
        for(int i=1;i<=color;i++)
         if(!ans[i])ansnum++,ansi=i;
        if(ansnum==1)printf("%d",colnum[ansi]);
         else printf("0");
        return 0;//suo you ans dian yi ding zu cheng yi ge qiang lian tong kuai!
    }
    View Code
  • 相关阅读:
    ibatis常用sql
    在eclipse中部署maven项目的问题
    如何成为一个设计师和程序员混合型人才
    一个程序员的读书笔记:程序设计的反思
    C# 中的 == 和 equals()有什么区别?
    2014百度之星资格赛解题报告:能量变换
    2014百度之星资格赛解题报告:Xor Sum
    2014百度之星资格赛解题报告:Labyrinth
    那些年我们一起追过的ACM
    最新全球排名前50网站前端开发语言统计
  • 原文地址:https://www.cnblogs.com/onioncyc/p/5888490.html
Copyright © 2011-2022 走看看