UVALive 4287 Proving Equivalence (强连通分量)
2024-09-03 18:03:26
把证明的关系看出一张图,最终就是要所有的点都在至少一个环中。环的判断和度数有关。
用tarjan找强连通分量,在一个强连通分量点已经等价缩点以后形成一个DAG,计算入度为0的点数a,
出度为0的b,取其中大的一个。特判强连通分量数为1的情况。
看懂tarjan算法以后还是比较简单的
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e4+;
const int maxm = 5e4+; int head[maxn],nxt[maxm],to[maxm],ecnt;
void addEdge(int u,int v)
{
nxt[ecnt] = head[u];
to[ecnt] = v;
head[u] = ecnt++;
} void initGraph(int n)
{
memset(head,-,sizeof(int)*(n+)); ecnt = ;
} int sccno[maxn],pre[maxn],low[maxn],dfs_clock,scc_cnt;
stack<int> stk; void tarjan(int u)
{
pre[u] = low[u] = ++dfs_clock;
stk.push(u);
for(int i = head[u]; ~i; i = nxt[i]){
int v = to[i];
if(!pre[v]){
tarjan(v);
low[u] = min(low[u],low[v]);
}else if(!sccno[v]){
low[u] = min(low[u],pre[v]);
}
}
if(low[u] == pre[u]){
scc_cnt++;
while(stk.size()){
int x = stk.top(); stk.pop();
sccno[x] = scc_cnt;
if(x == u) break;
}
}
} void find_scc(int n)
{
memset(pre,,sizeof(int)*(n+));
memset(sccno,,sizeof(int)*(n+));
scc_cnt = dfs_clock = ;
for(int i = ; i < n; i++){
if(!pre[i]) tarjan(i);
}
} int ind[maxn],outd[maxn]; int main()
{
//freopen("in.txt","r",stdin);
int T; scanf("%d",&T);
while(T--){
int n,m; scanf("%d%d",&n,&m);
initGraph(n);
for(int i = ; i < m; i++){
int u,v; scanf("%d%d",&u,&v);
addEdge(u-,v-);
}
find_scc(n);
if(scc_cnt == ) {
printf("0\n"); continue;
}
for(int i = ; i <= scc_cnt; i++) ind[i] = outd[i] = ;
for(int u = ; u < n; u++){
for(int i = head[u]; ~i; i = nxt[i]){
int v = to[i];
if(sccno[u] != sccno[v]) outd[sccno[u]]++,ind[sccno[v]]++;
}
}
int a = ,b = ;
for(int i = ; i <= scc_cnt; i++){
if(!outd[i]) b++;
if(!ind[i]) a++;
}
printf("%d\n",max(a,b));
}
return ;
}
最新文章
- js 练习
- Bash shell的内建命令:type
- archlinux 安装过程记录
- html5zero 网站模板 影片素材
- Java HashMap 源码解析
- java学习,从一个字符串中统计同一类型出现的次数
- div居中鼠标悬浮显示下拉列表
- 关于bootstrap--表单(按钮<;button>;效果、大小、禁用)
- Oracle的网络监听配置
- pythonpipinstallpymongo报错
- CopyOnWriteArrayList真的完全线程安全吗
- CF121E Lucky Array
- Android嵌套滑动不流畅记录随笔
- CentOS安装Nginx Pre-Built
- 工具篇-Json处理
- Spring整合MyBatis(简单登录Demo)
- 全志A33 lichee 搭建Qt App开发环境编写helloworld
- Oracle 删除重复数据只留一条(转)
- __Linux__操作系统发展史
- 最大流(EK)