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

    1051: [HAOI2006]受欢迎的牛

    Time Limit: 10 Sec  Memory Limit: 162 MB

    Submit: 6559  Solved: 3441

    [Submit][Status][Discuss]

    Description

      每一头牛的愿望就是变成一头最受欢迎的牛。现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎。 这种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认为牛C受欢迎。你的任务是求出有多少头牛被所有的牛认为是受欢迎的。

    Input

      第一行两个数N,M。 接下来M行,每行两个数A,B,意思是A认为B是受欢迎的(给出的信息有可能重复,即有可能出现多个A,B)

    Output

      一个数,即有多少头牛被所有的牛认为是受欢迎的。

    Sample Input

    3 3
    1 2
    2 1
    2 3

    Sample Output

    1

    HINT

    100%的数据N<=10000,M<=50000

    题解

    用tarjan求强联通,如果有多个DAG图,那么答案一定是0,因为一个DAG图中的点无法到达另一个DAG图中的点。

    如果只有一个DAG图,对于一个强联通内的点,一定能互相喜欢,很容易想到,若DAG图中出度为0的强联通只有一个,那么该强联通的点一定能被所以的点喜欢,若有多个出度为0的强联通,那么答案为0,因为两个出度为0的强联通不能相互喜欢。

    因为多个DAG的情况也存在多个出度为0的强联通,所以一起讨论即可。

    如果最终只有一个出度为0的强联通,则输出他内部点的个数,其他情况均输出0。

    代码

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<iostream>
    #include<stack>
    using namespace std;
    const int N=10005,M=50005;
    int n,m,k=1,cnt,tot,ans;
    int head[N],dfn[N],low[N],vis[N],belong[N],sum[N],out[N];
    struct edge{
    	int u,v,next;
    }e[M];
    void addedge(int u,int v){
    	e[k]=(edge){u,v,head[u]};
    	head[u]=k++;
    }
    stack<int>st;
    void dfs(int u){
    	dfn[u]=++cnt;
    	low[u]=cnt;
    	st.push(u);
    	int v;
    	for(int i=head[u];i;i=e[i].next){
    		v=e[i].v;
    		if(!dfn[v]){
    			dfs(v);
    			low[u]=min(low[u],low[v]);
    		}
    		else if(!vis[v]){
    			low[u]=min(low[u],dfn[v]);
    		}
    	}
    	if(dfn[u]==low[u]){
    		tot++;
    		while(1){
    			v=st.top();
    			st.pop();
    			belong[v]=tot;
    			vis[v]=1;
    			sum[tot]++;
    			if(v==u)break;
    		}
    	}
    }
    int main(){
    	scanf("%d%d",&n,&m);
    	int u,v;
    	for(int i=1;i<=m;i++){
    		scanf("%d%d",&u,&v);
    		addedge(u,v);
    	}
    	for(int i=1;i<=n;i++){
    		if(!dfn[i]){
    			dfs(i);
    		}
    	}
    	for(int i=1;i<=n;i++){
    		for(int j=head[i];j;j=e[j].next){
    			v=e[j].v;
    			if(belong[i]!=belong[v]){
    				out[belong[i]]++;
    			}
    		}
    	}
    	for(int i=1;i<=tot;i++){
    		if(out[i]==0&&ans){
    			printf("0
    ");
    			return 0;
    		}
    		if(out[i]==0)ans=sum[i];
    	}
    	printf("%d
    ",ans);
    	return 0;
    }
  • 相关阅读:
    Django资源大全
    iPhone企业应用实例分析之一:系统介绍和需求及主要用例
    iPhone SDK开发基础之使用UITabBarController组织和管理UIView
    iPhone企业应用实例分析之四:技术要点分析(1)
    头衔的权威暗示影响力
    什么是云存储技术与云存储服务?
    读书:《SEO实战密码》
    iPhone SDK开发基础之使用UINavigationController组织和管理UIView
    iPhone SDK开发基础之自定义仪表控件
    iPhone企业应用实例分析之三:程序框架分析
  • 原文地址:https://www.cnblogs.com/chezhongyang/p/7718097.html
Copyright © 2011-2022 走看看