#include
#include
#include
#include
using namespace std;
#define N 10010
#define M 100010
int n,m;
int cnt=-1,head[N];
struct Edge{int to,nxt;}e[M];
int idc,scc,dfn[N],low[N];
int vis[N],ins[N],bel[N];
stack <int> st;
void init()
{
idc=scc=0;cnt=-1;
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(ins,0,sizeof(ins));
memset(vis,0,sizeof(vis));
}
void adde(int u,int v)
{
e[++cnt].to=v;
e[cnt].nxt=head[u];
head[u]=cnt;
}
void Tarjan(int u)
{
dfn[u]=low[u]=idc++;
st.push(u);vis[u]=1;ins[u]=1;
for(int i=head[u];~i;i=e[i].nxt)
{
int v=e[i].to;
if(!vis[v]) Tarjan(v),low[u]=min(low[u],low[v]);
else if(ins[v]) low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
scc++;int v;
do
{
v=st.top();st.pop();
ins[v]=0;
bel[v]=scc;
}
while(v!=u);
}
}
int main()
{
while(scanf("%d%d",&n,&m)&&n+m)
{
init();
for(int i=1,u,v;i<=m;++i)
{
scanf("%d%d",&u,&v);
adde(u,v);
}
for(int i=1;i<=n;++i) if(!vis[i]) Tarjan(i);
puts(scc>=2?"No":"Yes");
}
return 0;
}
HDU 3072
代码如下:
#include
#include
#include
#include
#include
using namespace std;
#define inf 0x3f3f3f3f
#define N 50010
#define M 100010
int n,m,cnt=-1,head[N];
struct Edge{int to,nxt,w;}e[M];
int idc,scc,dfn[N],low[N];
int vis[N],ins[N],bel[N],ans[N];
stack <int> st;
void init()
{
idc=scc=0;cnt=-1;
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(bel,0,sizeof(bel));
memset(vis,0,sizeof(vis));
memset(ins,0,sizeof(ins));
}
void adde(int u,int v,int w)
{
e[++cnt].to=v;
e[cnt].w=w;
e[cnt].nxt=head[u];
head[u]=cnt;
}
void Tarjan(int u)
{
dfn[u]=low[u]=++idc;
vis[u]=1;ins[u]=1;st.push(u);
for(int i=head[u];~i;i=e[i].nxt)
{
int v=e[i].to;
if(!vis[v]) Tarjan(v),low[u]=min(low[u],low[v]);
else if(ins[v]) low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
scc++;int v;
do
{
v=st.top();st.pop();
ins[v]=0;
bel[v]=scc;
}
while(u!=v);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(int i=1,u,v,w;i<=m;++i)
{
scanf("%d%d%d",&u,&v,&w);
u++;v++;
adde(u,v,w);
}
for(int i=1;i<=n;++i) if(!vis[i]) Tarjan(i);
// for(int i=1;i<=n;++i) printf("%d ",bel[i]);puts("");
memset(ans,inf,sizeof(ans));
for(int i=1;i<=n;++i)
for(int j=head[i];~j;j=e[j].nxt)
{
int v=e[j].to;
if(bel[i]!=bel[v])
{
ans[bel[v]]=min(ans[bel[v]],e[j].w);
}
}
int sum=0;
for(int i=1;iprintf("%d\n",sum);
}
return 0;
}