P3183 [HAOI2016] FIG food chain DP & a.m. On DAY 1

Continued: DP & graph theory DAY 1 am

 

P3183 [HAOI2016] food chain

answer

◦ points given n and m edges directed acyclic food webs, which find how many very long food chain.

◦          n<=10^5,m<=2*10^5

>Solution

◦ topology dp Classic title

◦ set F [u] u is the number of nodes in the food chain end.

           

◦ topological order in order to transfer.

 

 When dealing with some of the small details:

1. Record each point how much penetration: easy topsort

2. How many out-degree: a degree of non-0 is a single point of the end of the food chain, where you can hit the mark with an array vis (in case you remember a single point on how to do QAQ)

3. Transfer topological order: the starting point of the food chain f [u] labeled 1, or after you transfer ye? ? ?

 

 

 

 

Code

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>

using namespace std;

inline int read()
{
    int ans=0;
    char last=' ',ch=getchar();
    while(ch<'0'||ch>'9') last=ch,ch=getchar();
    while(ch>='0'&&ch<='9') ans=ans*10+ch-'0',ch=getchar();
    if(last=='-') ans=-ans;
    return ans;
}

const int maxn=1e5+10;
const int maxm=2e5+10;
int n,m,ans=0;
int in[maxn],out[maxn],f[maxn];
int head[maxn],cnt=0;
bool vis[maxn];
struct node
{
    int u,v,nxt;
}edge[maxm];

void addedge(int u,int v)
{
    edge[++cnt].u =u;edge[cnt].v =v;
    edge[cnt].nxt =head[u];head[u]=cnt;
}

void topsort()
{
    queue<int>q;
    for(int u=1;u<=n;u++)
      if(!in[u])
        q.push(u),f[u]=1;
    while(!q.empty() )
    {
        int u=q.front() ;
        q.pop() ;
        for(int i=head[u];i;i=edge[i].nxt )
        {
            int v=edge[i].v ;
            f[v]+=f[u];
            in[v]--;
            if(!in[v]) q.push(v); 
        }
    } 
}

int main()
{
    n=read();m=read();
    for(int i=1,u,v;i<=m;i++)
    {
        u=read();v=read();
        addedge(u,v);
        in[v]++;
        out[u]++;
    }
    for(int i=1;i<=n;i++){  //打标记
        if(!out[i]&&in[i]) 
           vis[i]=1;
    } 
    topsort();
    for(int i=1;i<=n;i++){
    //    printf("f[%d]=%d ",i,f[i]);
        if(vis[i])
           ans+=f[i];
    }
      
    printf("%d",ans);
    
    
    return 0;
}

 

 

Guess you like

Origin www.cnblogs.com/xiaoyezi-wink/p/11355748.html