The Largest Clique (uva11324)

求图的缩点

#include<bits/stdc++.h>
using namespace std;

struct my{
   int v,next;
};

const int maxn=10000+10;
const int maxn1=100000+10;
my bian[maxn1];
my bian2[maxn1];
stack<int>s;
int sccno[maxn];
int adj[maxn];
int adj2[maxn];
int dp[maxn];
int w[maxn];
int fa;
int fa2;
int m,n,dfsnum;
int pre[maxn];
int lowlink[maxn];

void myinsert(int u,int v){
     bian[++fa].v=v;
     bian[fa].next=adj[u];
     adj[u]=fa;
}

void myinsert2(int u,int v){
     bian2[++fa2].v=v;
     bian2[fa2].next=adj2[u];
     adj2[u]=fa2;
}

void tarjan(int u){
     pre[u]=lowlink[u]=++dfsnum;
     s.push(u);
     for (int i=adj[u];i!=-1;i=bian[i].next){
        int v=bian[i].v;
        if(!pre[v]){
            tarjan(v);
            lowlink[u]=min(lowlink[v],lowlink[u]);
        }
        else if(!sccno[v]){
            lowlink[u]=min(lowlink[u],pre[v]);
        }
     }
     if(lowlink[u]==pre[u]){
        dfsnum++;
        for (;;){
            int e=s.top();
            s.pop();
            sccno[e]=dfsnum;
            if(e==u) break;
        }
     }
}
void init(){
  memset(bian,-1,sizeof(bian));
  memset(bian2,-1,sizeof(bian2));
  memset(adj2,-1,sizeof(adj2));
  memset(adj,-1,sizeof(adj));
  memset(lowlink,0,sizeof(lowlink));
  memset(pre,0,sizeof(pre));
  memset(sccno,0,sizeof(sccno));
  memset(dp,-1,sizeof(dp));
  fa=fa2=0;
  memset(w,0,sizeof(w));
  dfsnum=0;
  while(!s.empty()) s.pop();
}

void build(){
    for (int i=1;i<=n;i++){
        w[sccno[i]]++;
    }
    for (int i=1;i<=n;i++){
        for (int j=adj[i];j!=-1;j=bian[j].next){
            int v=bian[j].v;
            if (sccno[i] != sccno[v]){
                myinsert2(sccno[i],sccno[v]);
            }
        }
    }
}

int dfs(int u){
    if (dp[u] != -1) return dp[u];
    dp[u] = w[u];
    for (int i = adj2[u];i!=-1;i=bian2[i].next){
        int v = bian2[i].v;
        dp[u] = max(dp[u],dfs(v) + w[u]);
    }
    return dp[u];
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int u,v;
        init();
        scanf("%d%d",&n,&m);
        for (int i=1;i<=m;i++){
        scanf("%d%d",&u,&v);
        myinsert(u,v);
       }
       for (int i=1;i<=n;i++){
        if(!pre[i])
            tarjan(i);
       }
       build();
       int ans=0;
       for (int i=1;i<=n;i++)
            ans=max(ans,dfs(sccno[i]));
        printf("%d\n", ans);
    }
return 0;
}
posted @ 2018-01-07 11:58  lmjer  阅读(174)  评论(0编辑  收藏  举报