洛谷B3611 【模板】传递闭包 floyd/bitset

题目链接:https://www.luogu.com.cn/problem/B3611

参考题解:https://www.luogu.com.cn/blog/53022/solution-b3611

floyd

#include <bits/stdc++.h>
using namespace std;
const int maxn = 101;
int n, f[maxn][maxn];

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            scanf("%d", &f[i][j]);
    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                f[i][j] |= f[i][k] & f[k][j];
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (j > 1) putchar(' ');
            putchar(f[i][j] ? '1' : '0');
        }
        puts("");
    }
    return 0;
}

bitset优化

#include <bits/stdc++.h>
using namespace std;
const int maxn = 101;
int n, a;
bitset<maxn> f[maxn];

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            scanf("%d", &a), f[i][j] = a;
    for (int j = 1; j <= n; j++)
        for (int i = 1; i <= n; i++)
            if (f[i][j])
                f[i] |= f[j];
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (j > 1) putchar(' ');
            putchar(f[i][j] ? '1' : '0');
        }
        puts("");
    }
    return 0;
}
posted @ 2023-12-26 18:02  quanjun  阅读(47)  评论(0编辑  收藏  举报