Poj 1236 -- network of schools

Source: Internet
Author: User

Tarjan Algorithm

Note: For a strongly connected graph, the output value is 0 1.

Point reduction using the Tarjan algorithm.

The first question is the number of input points = 0.

The number of edges added in the second question is max (number of inbound vertex = 0, and number of outbound vertex = 0 ). Now let's write down the theorem.

#include<iostream>#include<cstdio>#include<cstring>using namespace std;#define maxm 21000#define maxn 220int n;int head[maxn],cnt;int v[maxm],next[maxm];int dfn[maxn],low[maxn],step;int sta[maxn],top;int ID[maxn],IdNum;int d_in[maxn],d_out[maxn];bool vis[maxn];void add(int a,int b){v[cnt]=b;next[cnt]=head[a];head[a]=cnt++;}void Init(){memset(vis,0,sizeof(vis));memset(d_in,0,sizeof(d_in));memset(d_out,0,sizeof(d_out));memset(head,-1,sizeof(head));memset(dfn,0,sizeof(dfn));memset(low,0,sizeof(low));IdNum=top=step=cnt=0;}void tarjan(int u){low[u]=dfn[u]=++step;sta[++top]=u;vis[u]=1;for(int i=head[u];~i;i=next[i]){int to=v[i];if(!dfn[to]){tarjan(to);low[u]=min(low[u],low[to]);}elseif(vis[to])low[u]=min(low[u],dfn[to]);}if(low[u]==dfn[u]){int x;IdNum++;do{x=sta[top--];vis[x]=0;ID[x]=IdNum;}while(u!=x);}}void build(){for(int i=1;i<=n;i++)for(int j=head[i];~j;j=next[j]){int to=v[j];if(ID[i]!=ID[to]){d_in[ID[to]]++;d_out[ID[i]]++;}}}int main(){int x;while(~scanf("%d",&n)){Init();for(int i=1;i<=n;i++){scanf("%d",&x);while(x){add(i,x);scanf("%d",&x);}}for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i);build();int ans1=0;int ans2=0;for(int i=1;i<=IdNum;i++){if(d_in[i]==0)ans1++;if(d_out[i]==0)ans2++;}if(IdNum!=1)printf("%d\n%d\n",ans1,max(ans1,ans2));elseprintf("1\n0\n");}return 0;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.