1. 程式人生 > >bzoj 1093: [ZJOI2007]最大半連通子圖

bzoj 1093: [ZJOI2007]最大半連通子圖

sha 表示圖 sin back script 不同的 sam scrip 註意

Description

  一個有向圖G=(V,E)稱為半連通的(Semi-Connected),如果滿足:?u,v∈V,滿足u→v或v→u,即對於圖中任意
兩點u,v,存在一條u到v的有向路徑或者從v到u的有向路徑。若G‘=(V‘,E‘)滿足V‘?V,E‘是E中所有跟V‘有關的邊,
則稱G‘是G的一個導出子圖。若G‘是G的導出子圖,且G‘半連通,則稱G‘為G的半連通子圖。若G‘是G所有半連通子圖
中包含節點數最多的,則稱G‘是G的最大半連通子圖。給定一個有向圖G,請求出G的最大半連通子圖擁有的節點數K
,以及不同的最大半連通子圖的數目C。由於C可能比較大,僅要求輸出C對X的余數。

Input

  第一行包含兩個整數N,M,X。N,M分別表示圖G的點數與邊數,X的意義如上文所述接下來M行,每行兩個正整
數a, b,表示一條有向邊(a, b)。圖中的每個點將編號為1,2,3…N,保證輸入中同一個(a,b)不會出現兩次。N ≤1
00000, M ≤1000000;對於100%的數據, X ≤10^8

Output

  應包含兩行,第一行包含一個整數K。第二行包含整數C Mod X.

Sample Input

6 6 20070603
1 2
2 1
1 3
2 4
5 6
6 4

Sample Output

3
3

HINT

Source

對於這種有向圖的問題一般的解法就是tarjan縮點後轉為DAG上的問題,然後用拓撲序dp。

這個題縮完點後就是求DAG上的最長路及最長路的方案數,可以用拓撲序dp很好的解決。

至於方案數可以直接在轉移的時候由加法原理直接統計(註意去掉重邊!!!)

問題很經典就不再贅述

// MADE BY QT666
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int Inf=20010411;
const int M=1500000;
const int N=150000;
int gi()
{
  int x=0;
  char ch=getchar();
  while(ch<‘0‘||ch>‘9‘) ch=getchar();
  while(ch>=‘0‘&&ch<=‘9‘) x=x*10+ch-‘0‘,ch=getchar();
  return x;
}
int head[N],to[M],nxt[M],sum,dfn[N],low[N],cnt=1,tot,vis[N],ans,tt,zhan[N],fr[N],size[N];
int n,m,mod,ru[N],f[N],num[N],mark[N],ans1,ans2;
queue<int>q;
vector<int>p[N];
void tarjan(int x) {
  dfn[x]=low[x]=++tt;int y;
  vis[x]=1,zhan[++sum]=x;
  for(int i=head[x];i;i=nxt[i]) {
    y=to[i];
    if(!dfn[y]) {
      tarjan(y);low[x]=min(low[x],low[y]);
    }
    else if(vis[y]) low[x]=min(low[x],dfn[y]);
  }
  if(dfn[x]==low[x]) {
    tot++;
    do {
      y=zhan[sum--];
      vis[y]=0;fr[y]=tot;size[tot]++;
    } while(y!=x);
  }
}
void pre(){
    for(int i=1;i<=n;i++)
    for(int j=head[i];j;j=nxt[j])
        if(fr[to[j]]!=fr[i]){
        p[fr[i]].push_back(fr[to[j]]);
        ru[fr[to[j]]]++;
        }
    for(int i=1;i<=tot;i++){
    f[i]=size[i],num[i]=1;ans1=max(f[i],ans1);
    if(!ru[i]) q.push(i);
    }
}
void lnk(int x,int y){
 to[++cnt]=y,nxt[cnt]=head[x],head[x]=cnt;
}
void top_dp(){
    while(!q.empty()){
    int x=q.front();q.pop();
    for(int i=0;i<p[x].size();i++){
        int y=p[x][i];ru[y]--;
        if(!ru[y]) q.push(y);
        if(mark[y]==x) continue;
        if(f[x]+size[y]>f[y]) f[y]=f[x]+size[y],num[y]=0;
        if(f[x]+size[y]==f[y]) num[y]=(num[y]+num[x])%mod;
        ans1=max(ans1,f[y]);
        mark[y]=x;
    }
    }
}
int main()
{
    n=gi(),m=gi(),mod=gi();
    for(int i=1;i<=m;i++){
    int x=gi(),y=gi();lnk(x,y);
    }
    for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i);
    pre();top_dp();
    for(int i=1;i<=tot;i++) if(f[i]==ans1) ans2=(ans2+num[i])%mod;
    printf("%d\n%d",ans1,ans2);
    return 0;
}

  

bzoj 1093: [ZJOI2007]最大半連通子圖