HDU 1704 Rank floyd求传递闭包 || bfs

来源:互联网 发布:小天才早教机软件下载 编辑:程序博客网 时间:2024/05/21 09:28

题目:

http://acm.hdu.edu.cn/showproblem.php?pid=1704

题意:

nmx>yy>zx>z

思路:

floydbfs
floyd:

#include <bits/stdc++.h>using namespace std;const int N = 500 + 10, INF = 0x3f3f3f3f;bool mp[N][N];void floyd(int n){    for(int k = 1; k <= n; k++)        for(int i = 1; i <= n; i++)            if(mp[i][k])                for(int j = 1; j <= n; j++)                    mp[i][j] = mp[i][j] || (mp[i][k] && mp[k][j]);}int main(){    int t, n, m;    scanf("%d", &t);    while(t--)    {        memset(mp, 0, sizeof mp);        scanf("%d%d", &n, &m);        int v, u;        for(int i = 1; i <= m; i++)        {            scanf("%d%d", &v, &u);            mp[v][u] = true;        }        floyd(n);        int ans = 0;        for(int i = 1; i <= n; i++)            for(int j = i+1; j <= n; j++)                if(! mp[i][j] && ! mp[j][i]) ans++;        printf("%d\n", ans);    }    return 0;}

bfs:

#include <bits/stdc++.h>using namespace std;const int N = 500 + 10, INF = 0x3f3f3f3f;struct edge{    int to, next;}g[N*N];int cnt, head[N];bool vis[N];void add_edge(int v, int u){    g[cnt].to = u, g[cnt].next = head[v], head[v] = cnt++;}int bfs(int v){    queue<int> que;    memset(vis, 0, sizeof vis);    int tot = 0;    que.push(v), vis[v] = true;    while(! que.empty())    {        int v = que.front(); que.pop();        for(int i = head[v]; i != -1; i = g[i].next)        {            int u = g[i].to;            if(! vis[u]) que.push(u), vis[u] = true, tot++;        }    }    return tot;}int main(){    int t, n, m;    scanf("%d", &t);    while(t--)    {        cnt = 0;        memset(head, -1, sizeof head);        scanf("%d%d", &n, &m);        int v, u;        for(int i = 1; i <= m; i++)        {            scanf("%d%d", &v, &u);            add_edge(v, u);        }        int num = 0;        for(int i = 1; i <= n; i++) num += bfs(i);        printf("%d\n", n * (n-1) / 2 - num);    }    return 0;}