SOJ 12259 Message Relay (dfs,图联通)

本文详细介绍了如何使用Floyd算法求传递闭包,并通过枚举判断来找出有向图中的环以及进入环的点。提供了一个简单有效的解决方案,包括对输入数据的读取和输出结果的展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:找出一个有向图中的环以及进入环的点。。(如果我没有理解错的话。。)一开始用Floyd求传递闭包,然后枚举判断竟然wa了。。于是利用题目条件,每个点出发最多一条边,,写了个最简单的。。有时间直接求联通分量来验证一下。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <map>
using namespace std;

#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define REP(i, s, t) for(int (i)=(s);(i)<=(t);++(i))
#define UREP(i, s, t) for(int (i)=(s);(i)>=(t);--(i))

typedef long long LL;

const int maxn = 1005;
int nxt[maxn];
int vis[maxn];
int pre[maxn];

bool dfs(int now) {
    pre[now] = 1;
    int v = nxt[now];
    if (v == 0) return false;
    if (pre[v]) return true;
    return dfs(v);
}

int main() {
    freopen("input.in", "r", stdin);
    int n, tmp;
    while (cin >> n) {
           REP(i, 1, n) cin >> nxt[i];
           memset(vis, 0, sizeof(vis));
           REP(i, 1, n)
            if (!vis[i]) {
                memset(pre, 0, sizeof(pre));
                if (dfs(i) == false) {
                    REP(j, 1, n)
                        if (pre[j]) vis[j] = 1;
                }
            }
           int ans = 0;
           REP(i, 1, n) if (vis[i]) ++ans;
           cout << ans << endl;
    }

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值