首页 > 代码库 > BZOJ 2208 连通数(强连通分量)
BZOJ 2208 连通数(强连通分量)
先缩点,对于缩完点后的DAG,可以直接在每个scc dfs一次就可以求出终点是这个scc的点的点对个数。
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi 3.1415926535 # define eps 1e-9 # define MOD 1000000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())==‘-‘) flag=1; else if(ch>=‘0‘&&ch<=‘9‘) res=ch-‘0‘; while((ch=getchar())>=‘0‘&&ch<=‘9‘) res=res*10+(ch-‘0‘); return flag?-res:res; } void Out(int a) { if(a<0) {putchar(‘-‘); a=-a;} if(a>=10) Out(a/10); putchar(a%10+‘0‘); } const int N=2005; //Code begin... struct Edge{int p, next;}edge[N*N*2]; int head[N], cnt=1; char s[N][N]; int G[N][N], n; int Low[N], DFN[N], Stack[N], Belong[N], Index, top, scc, num[N]; bool Instack[N], vis[N][N], mark[N]; LL siz[N]; void add_edge(int u, int v){edge[cnt].p=v; edge[cnt].next=head[u]; head[u]=cnt++;} void Tarjan(int u){ Low[u]=DFN[u]=++Index; Stack[top++]=u; Instack[u]=true; FOR(v,1,n) { if (!G[u][v]) continue; if (!DFN[v]) { Tarjan(v); if (Low[u]>Low[v]) Low[u]=Low[v]; } else if (Instack[v]&&Low[u]>DFN[v]) Low[u]=DFN[v]; } int v; if (Low[u]==DFN[u]) { scc++; do{ v=Stack[--top]; Instack[v]=false; Belong[v]=scc; num[scc]++; }while (v!=u); } } void solve(int nn){ mem(DFN,0); mem(Instack,0); mem(num,0); Index=scc=top=0; FOR(i,1,nn) if (!DFN[i]) Tarjan(i); } void dfs(int x, int fa){ siz[x]+=num[x]*num[fa]; mark[x]=1; for (int i=head[x]; i; i=edge[i].next) { int v=edge[i].p; if (mark[v]) continue; dfs(v,fa); } } int main () { LL ans=0; scanf("%d",&n); FOR(i,1,n) scanf("%s",s[i]+1); FOR(i,1,n) FOR(j,1,n) G[i][j]=s[i][j]-‘0‘; solve(n); FOR(i,1,n) FOR(j,1,n) { if (!G[i][j]) continue; int u=Belong[i], v=Belong[j]; if (u==v||vis[u][v]) continue; add_edge(u,v); vis[u][v]=true; } FOR(i,1,scc) mem(mark,0), dfs(i,i); FOR(i,1,scc) ans+=siz[i]; printf("%lld\n",ans); return 0; }
BZOJ 2208 连通数(强连通分量)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。