【题解】 [HAOI2016]食物链 (拓扑排序)

懒得复制,直接贴链接吧

Solution:

  • 水题一道,注意单独一个点的不算在食物链中,也就是\(in[i]==0\) \(out[i]==0\)的点就不计算

Code:

//It is coded by Ning_Mew on 3.20
#include<bits/stdc++.h>
using namespace std;

const int maxn=1e5+7;
const int maxm=2e5+7;

int n,m;
int head[maxn],cnt=0,in[maxn],out[maxn];
int dp[maxn],ans=0;
struct Edge{
  int nxt,to;
}edge[maxm];

void add(int from,int to){
  edge[++cnt].nxt=head[from];
  edge[cnt].to=to;
  head[from]=cnt;
}
void work(){
  queue<int>q;
  while(!q.empty())q.pop();
  for(int i=1;i<=n;i++){
    if(in[i]==0&&out[i]!=0)dp[i]=1,q.push(i);
  }
  while(!q.empty()){
    int u=q.front();q.pop();
    for(int i=head[u];i!=0;i=edge[i].nxt){
      int v=edge[i].to;
      in[v]--;dp[v]+=dp[u];
      if(in[v]==0)q.push(v);
    }
  }
}
int main(){
  scanf("%d%d",&n,&m);
  memset(in,0,sizeof(in));
  memset(out,0,sizeof(out));
  memset(dp,0,sizeof(dp));
  for(int i=1;i<=m;i++){
    int x,y;scanf("%d%d",&x,&y);
    add(x,y);in[y]++;out[x]++;
  }
  work();
  for(int i=1;i<=n;i++){
    if(out[i]==0)ans+=dp[i];
  }
  printf("%d\n",ans);
  return 0;
}

posted @ 2018-03-20 15:58  Ning_Mew  阅读(346)  评论(0编辑  收藏  举报