The question test instructions clear, that is, given a set of letters of the size of the relationship to determine whether they can form a unique topological sequence. is a typical topological sort, but there are three types of output formats:
1. The letter sequence is ordered and output sequentially;
2. The sequence does not determine whether it is orderly;
3. There is a contradiction between the sequence alphabetical order, that is, a ring exists.
And these three forms of judgment are in order: first to determine whether there is a ring (3), and then determine whether the order (1), finally can determine whether the results (2). Note: for (2) the entire graph must be traversed, and (1) and (3) Once the result is reached, the subsequent input is not processed.
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <vector>5#include <algorithm>6 7 using namespacestd;8 9 Const intn=5005;Tenvector<int>G[n]; One intDfn[n],low[n],dg[n],tim; A BOOLVis[n],map[n][n]; - intN,r; - the voidTarjan (intUintFA) - { -dfn[u]=low[u]=++Tim; -vis[u]=1; + for(intI=0; I<g[u].size (); i++) - { + intv=G[u][i]; A if(V==FA)Continue; at if(!Dfn[v]) - { - Tarjan (V, u); -low[u]=min (low[u],low[v]); - } - Else if(Vis[v]) low[u]=min (low[u],dfn[v]); in } - } to voidInit () + { -memset (DFN,0,sizeof(DFN)); thememset (Low,0,sizeof(low)); *memset (Vis,0,sizeof(VIS)); $tim=0;Panax NotoginsengTarjan (1,-1); - } the intMain () + { A while(~SCANF ("%d%d",&n,&R)) the { + for(intI=1; i<=n;i++) - g[i].clear (); $memset (Map,0,sizeof(map)); $ intu,v; - for(intI=0; i<r;i++) - { thescanf"%d%d",&u,&v); - if(!Map[u][v])Wuyi { the G[u].push_back (v); - g[v].push_back (u); Wumap[u][v]=map[v][u]=1; - } About } $ - init (); -memset (DG,0,sizeof(DG)); - A for(intu=1; u<=n;u++) + for(intI=0; I<g[u].size (); i++) the { - intv=G[u][i]; $ if(Low[u]!=low[v]) dg[low[u]]++; the } the the intCnt=0; the for(intI=1; i<=n;i++) - if(dg[i]==1) cnt++; inprintf"%d\n", (cnt+1)/2); the } the}
POJ1094 alphabetical order (topological sort)