【bzoj1612】【Usaco2008 Jan】Cow Contest奶牛的比赛 题解&代码

题目链接:
http://www.lydsy.com/JudgeOnline/problem.php?id=1612
题解:
对于这种题我们发现可以dfs求出一共有多少头牛比他强,一共有多少头牛比他弱,当比他强的牛数加比他弱的牛数等于总数减一时,这头牛的排名就能确定。
代码:

#include
#include
#include
#include
using namespace std;
int n,q,tot,flag;
struct node{
    int v;int w;int next;
}edge1[9009],edge2[9009];
int head1[105],head2[105],tot1,tot2;
bool vis[105];
void addedge1(int u,int v)
{
    tot1++;
    edge1[tot1].v=v;
    edge1[tot1].next=head1[u];
    head1[u]=tot1;
}
void addedge2(int u,int v)
{
    tot2++;
    edge2[tot2].v=v;
    edge2[tot2].next=head2[u];
    head2[u]=tot2;
}
int xsum,dsum;
void dfs1(int x)
{
    vis[x]=1;
    dsum++;
    for (int i=head1[x];i!=0;i=edge1[i].next)
    {
        int v=edge1[i].v;
        if (vis[v]==0)
        dfs1(v); 
    }
}
void dfs2(int x)
{
    xsum++;
    vis[x]=1;
    for (int i=head2[x];i!=0;i=edge2[i].next)
    {
        int v=edge2[i].v;
        if (vis[v]==0)
        dfs2(v); 
    }
}
int m;
int main()
{
    scanf("%d%d",&n,&m);
    tot1=1;tot2=1;
    for (int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        addedge1(x,y);
        addedge2(y,x);
    }
    int ans=0;
    for (int i=1;i<=n;i++)
    {
        memset(vis,0,sizeof(vis));
        xsum=0,dsum=0;
        dfs1(i);
        memset(vis,0,sizeof(vis));
        dfs2(i);
        if (xsum+dsum==n+1)
        ans++;
    }
    printf("%d\n",ans);
}

你可能感兴趣的:(bzoj)