COJ 1081 集训队分组

http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1081

不是太会写拓扑排序,所以再写一遍。

/*Accepted    880 kb    268 ms    C++/    1671 B    2012-07-29 17:08:30*/

#include<cstdio>

#include<cstring>

#include<cstdlib>



const int MAXN = 1 << 10;

const int MAXM = 10010;



int N, K, M, first[MAXN], e, next[MAXM], v[MAXM];

int topo[MAXN], cnt, vis[MAXN];



void addedge(int x, int y)

{

    v[e] = y;

    next[e] = first[x], first[x] = e ++;

}



void ReadGraph()

{

    int i, x, y;

    memset(first, -1, sizeof first);

    e = 0;

    for(i = 0; i < M; i ++)

    {

        scanf("%d%d", &x, &y);

        addedge(x, y);

    }

}



void dfs(int cur)

{

    int i;

    vis[cur] = 1;

    for(i = first[cur]; i != -1; i = next[i])

        if(!vis[v[i]])

            dfs(v[i]);

    topo[cnt --] = cur;

}



void toposort()

{

    int i;

    cnt = N;

    memset(vis, 0, sizeof vis);

    for(i = 1; i <= N; i ++)

        if(!vis[i])

            dfs(i);

}



void Search(int cur)

{

    int i;

    vis[cur] = 1;

    for(i = first[cur]; i != -1; i = next[i])

        if(!vis[v[i]])

            Search(v[i]);

}



bool judge()

{

    int i, j;

    for(i = 1; i <= K; i ++)

    {

        memset(vis, 0, sizeof vis);

        Search(topo[i]);

        for(j = K + 1; j <= N; j ++)

            if(!vis[topo[j]])

                return false;

    }

    return true;

}



int main()

{

    while(scanf("%d%d%d", &N, &K, &M) == 3)

    {

        ReadGraph();

        toposort();

        bool ok = judge();

        if(ok)

            printf("YES\n");

        else

            printf("NO\n");

    }

    return 0;

}

 

你可能感兴趣的:(分组)