首页 技术 正文
技术 2022年11月14日
0 收藏 713 点赞 4,644 浏览 1368 个字
#include <cstring>
#include <cstdlib>
#include <cstdio>
缩点的好处就是可以将乱七八糟的有向图 转化为无环的有向图
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
using namespace std;
#define MAXN 200010
#define clr(x,k) memset((x),(k),sizeof(x))
struct node
{
int st,to,next;
}
edge[MAXN];
int n,m,ct,id;
int head[MAXN],low[MAXN],dfn[MAXN],belong[MAXN],in[MAXN],to[MAXN];
//DFN[i]表示 遍历到 i 点时是第几次dfs
//Low[u] 表示 以u点为父节点的 子树 能连接到 [栈中] 最上端的点 的DFN值
bool instack[MAXN];
stack<int>q;
void add_e(int i,int u,int v)
{
edge[i].st=u;
edge[i].to=v;
edge[i].next=head[u];
head[u]=i;
}
void tarjan(int i)
{
int j;
dfn[i]=low[i]=++id;
q.push(i);
instack[i]=1;
for(int u=head[i]; ~u; u=edge[u].next)
{
j=edge[u].to;
if(dfn[j]==0)
{
tarjan(j);
if(low[i]>low[j])
low[i]=low[j];
}
else if(instack[j]&&low[i]>low[j])
low[i]=dfn[j];
}
if(dfn[i]==low[i])
{
ct++;
do
{
j=q.top();
q.pop();
instack[j]=0;
belong[j]=ct;
}
while(i!=j);
}
}
int main()
{
int t,i,u,v,sum1,sum2;
cin>>t;
while(t--)
{
clr(head,-1);
clr(low,0);
clr(dfn,0);
clr(belong,0);
clr(in,0);
clr(to,0);
while(!q.empty())
q.pop();
cin>>n>>m;
for(i=0; i<m; i++)
{
cin>>u>>v;
add_e(i,u,v);
}
id=ct=0;
for(i=1; i<=n; i++)
{
if(!dfn[i])
tarjan(i);
}
if(ct==1)
{
cout<<0<<endl;
continue;
}
for(i=1; i<=ct; i++)
{
in[i]=to[i]=0;
}
for(i=0; i<m; i++)// 利用染色进行缩点 新的图的点的坐标为第i个强连通分量
{
if(belong[edge[i].st]!=belong[edge[i].to])
{
in[belong[edge[i].st]]++;
to[belong[edge[i].to]]++;
}
}
sum1=sum2=0;
for(i=1; i<=ct; i++)
{
if(in[i]==0)
sum1++;
if(to[i]==0)
sum2++;
}
cout<<max(sum1,sum2)<<endl;
}
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,027
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,518
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,365
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,146
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,780
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,857