POJ2186 POPULAR COW

链接:http://poj.org/problem?id=2186

题意:给你N个点,然后在给你N条有向边,然后让你找出这样的点S,S满足条件图上任意一点都能到达S。

要想满足任意一点都能到达,首先满足图连通,然后满足将图缩点后形成一个棵树,树的特征是可以有且只有一个点的出度为0。

然后代码如下:

 #include <iostream>
#include <vector>
#include <queue>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stack> using namespace std;
const int maxn = ; struct edge
{
int u,v,val;
};
int dfn[],low[],belong[],inst[];
vector<edge> edges;
vector<int>g[maxn];
stack<int>st;
int bcnt,cnt,time; void init(int n)
{
int i;
for(i =;i <= n;i++)
g[i].clear(); edges.clear();
time = ;bcnt = cnt = ;
return ;
}
void addedge(int u,int v,int val)
{
edges.push_back((edge){u,v,});
g[u].push_back(cnt);
cnt++; return ;
}
void tarjan(int i)
{
int j;
dfn[i] = low[i] = ++time;
inst[i] = ;
st.push(i); for(j = ;j < g[i].size();j++)
{
edge e;
e = edges[g[i][j]];
int v;
v = e.v;
if(!dfn[v])
{
tarjan(v);
low[i] = min(low[i],low[v]);
}
else if(inst[v] && dfn[v] < low[i])
low[i] = dfn[v];
}
if(dfn[i] == low[i])
{
//cout<<i<<"****"<<endl;
bcnt++;
do
{
j = st.top();
st.pop();
inst[j] = ;
belong[j] = bcnt;
//printf("%d *",j);
}
while(j != i);
//puts("");
} }
void tarjans(int n)
{
int i;
bcnt = time = ;
while(!st.empty())st.pop();
memset(dfn,,sizeof(dfn)); memset(inst,,sizeof(inst));
memset(belong,,sizeof(belong));
for(i = ;i <= n;i++)
if(!dfn[i])tarjan(i);
}
int main()
{
int n,m;
//freopen("in.txt","r",stdin);
while(~scanf("%d %d",&n,&m))
{
int a,b,i;
init(n);
for(i = ;i < m;i++)
{
scanf("%d %d",&a,&b);
addedge(a,b,); }
tarjans(n);
//cout<<bcnt<<endl;
int leap = ,flag = ;
int bcnt0,j;
int outbc[];
memset(outbc,,sizeof(outbc));
for(i = ;i <= n;i++)
{
for(j = ;j < g[i].size();j++)
{
int v;
v = edges[g[i][j]].v;
if(belong[i] != belong[v]){
if(outbc[belong[i]] == )
leap++;
outbc[belong[i]] = ;
}
}
}
if(leap == bcnt-)
{
int ans;
ans = ;
for(i = ;i < bcnt+;i++)
{
if(outbc[i] == )
break;
}
for(j = ;j <= n;j++)
if(belong[j] == i)
ans++; printf("%d\n",ans);
}
else
puts(""); }
return ;
}
上一篇:8月10日 微软MVP巡讲 Windows 开发专题活动


下一篇:SpringMVC配置字符编码过滤器CharacterEncodingFilter来解决表单乱码问题