博客
关于我
E. Strictly Positive Matrix [强联通+矩阵幂转图论+缩点] 好题
阅读量:537 次
发布时间:2019-03-08

本文共 1702 字,大约阅读时间需要 5 分钟。

为了确定是否存在一个正整数 ( k ) 使得矩阵 ( a^k ) 是严格正的,我们需要分析矩阵所表示的有向图的强连通性。具体来说,我们需要判断该图是否为强连通图。

方法思路

  • 矩阵分析转换为图论问题:将矩阵 ( a ) 视为一个有向图,其中 ( a[i][j] > 0 ) 表示存在一条边从节点 ( i ) 指向节点 ( j )。
  • 强连通性判断:使用 Tarjan 算法来检测图的强连通分量数量。如果强连通分量数量为 1,则图是强连通的,否则不是。
  • DFS 算法:执行深度优先搜索 (DFS) 来计算每个节点的最低入时间 (Low value),并确定强连通分量的数量。
  • 解决代码

    #include 
    #include
    #include
    #include
    #include
    using namespace std;const int MAX_N = 2002;const int MOD = 1e9 + 7;const int INF = 0x3f3f3f3f;vector
    > adj(MAX_N);int DFN[MAX_N], LOW[MAX_N], s = 1, top = 0, cnt = 0;bool visited[MAX_N];stack
    stack;void dfs_iterative(int u) { stack.push(u); int index = 0; while (!stack.empty()) { int v = stack.top(); if (v != u && DFN[v] != 0) { stack.pop(); continue; } if (DFN[v] != 0) { if (LOW[u] > DFN[v]) LOW[u] = DFN[v]; continue; } DFN[v] = top++; LOW[v] = top++; visited[v] = true; if (index == 0) { index = 1; } else if (index == 1) { index = 2; } else { stack.push(u); index = 0; continue; } for (int i = 0; i < adj[v].size(); ++i) { int to = adj[v][i]; if (!visited[to]) { stack.push(to); index = 0; } else if (DFN[to] != 0 && !visited[to]) { if (LOW[u] > DFN[to]) LOW[u] = DFN[to]; } } }}int main() { int n; read(n); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { int x; read(x); if (x > 0) { adj[i].push_back(j); } } } for (int i = 1; i <= n; ++i) { if (!visited[i]) { dfs_iterative(i); if (LOW[i] == DFN[i]) { cnt++; } } } if (cnt == 1) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0;}

    代码解释

  • 输入处理:读取矩阵并构建邻接表 adj。
  • DFS 实现:使用非递归 DFS 来计算每个节点的最低入时间和强连通分量数量。
  • 强连通性判断:检查强连通分量的数量。如果为 1,输出 "YES",否则输出 "NO"。
  • 该方法通过图论中的强连通性检测,确保了算法的正确性和高效性,能够在较大规模的输入下快速得到结果。

    转载地址:http://jkkiz.baihongyu.com/

    你可能感兴趣的文章
    python系列【仅供参考】:python 远程rdp
    查看>>
    python基础
    查看>>
    Python基本语法与变量类型
    查看>>
    python基本数据类型(容器)- tuple list dict set
    查看>>
    python基本工资的调整方案_Python薪资又涨了!这可咋办!
    查看>>
    Python基准测试和性能分析内存管理和垃圾回收
    查看>>
    Python基于RESTful风格的接口自动化测试实战
    查看>>
    python基于flask搭建http服务(四)—— Docker容器化部署
    查看>>
    python基于flask搭建http服务(二)—— 实现Excel上传、数据清洗、入库
    查看>>
    python基于flask搭建http服务(三)—— 使用gunicorn部署项目
    查看>>
    python基于flask搭建http服务(一)—— 实现数据查询和Excel导出
    查看>>
    Python块键盘/鼠标输入
    查看>>
    python在心理学研究中的应用有哪些_心理学在线研究可用平台简介和应用进展
    查看>>
    python在使用HTMLTestRunner时,报告为空,错误提示<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf_8'>...
    查看>>
    python在gpu上运行_【python】python开启GPU加速
    查看>>
    Python在def函数中使用for循环
    查看>>
    Python在def函数中使用for循环
    查看>>
    Python在Conda环境中,但在Windows虚拟环境中没有激活
    查看>>
    python系列【仅供参考】:python pip 错误 ModuleNotFoundError: No module named pip._internal 解决办法
    查看>>
    python图像条状状噪声,使用PYTHON PIL从验证码图像中删除背景嘈杂的线条
    查看>>