Maximum Clique

Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4195    Accepted Submission(s): 2220


Problem Description
Given a graph G(V, E), a clique is a sub-graph g(v, e), so that for all vertex pairs v1, v2 in v, there exists an edge (v1, v2) in e. Maximum clique is the clique that has maximum number of vertex.
 

Input
Input contains multiple tests. For each test:

The first line has one integer n, the number of vertex. (1 < n <= 50)

The following n lines has n 0 or 1 each, indicating whether an edge exists between i (line number) and j (column number).

A test with n = 0 signals the end of input. This test should not be processed.
 

Output
One number for each test, the number of vertex in maximum clique.
 

Sample Input
5 0 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1 1 0 1 1 1 1 1 0 0
 

Sample Output
4
 

题目大意:

                给你一个无向图求最大的完全子图,最大团问题

题目思路:

                对于最大团问题有很多种解法,可以参考该博客:最大团

               普通的方法是搜索,也就是枚举点的组合,看是否可以构成完全图,这样复杂度很高,所以我们考虑剪纸,如果当前搜索到的个数加上剩余的点不大于当前搜索到的最大值则返回,这样可以省掉不少时间,但复杂度还是不是很好,然后我们可以考虑dp来降低复杂度,我们可以从后往前枚举点,dp[i]表示第i个点和它之后点所能组成的最大值,那么最后一个点就是dp[n]=1因为只有一个点,然后遍历点,让改点加入后面的组合中看是否能加入和更新最大值!


AC代码:

dp优化写法1(一般):

#include<cstring>
#include<cstdio>

const int maxn = 55;

int mp[maxn][maxn];
int dp[maxn],num[maxn];
int n,ans;

bool check(int deep,int x){
    for(int i=1;i<=deep;i++){
        if(!mp[x][num[i]])return false;
    }
    return true;
}

void dfs(int deep,int x){
   if(deep>ans)ans=deep;
    if(deep+dp[x]<=ans||deep+n-x+1<=ans)return ;  //剪纸
    for(int i=x;i<=n;i++){
        if(check(deep,i)){
            num[deep+1]=i;
            dfs(deep+1,i);
        }
    }

}

int main()
{
    while(~scanf("%d",&n),n){
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&mp[i][j]);
        memset(dp,0,sizeof(dp));
        dp[n]=ans=1;
        for(int i=n-1;i>=1;i--){
            num[1]=i;
            dfs(1,i+1);
            dp[i]=ans;
        }
        printf("%d\n",ans);
    }

    return 0;
}


dp优化写法2(较优):

#include<cstdio>

const int maxn = 65;

int n,num;
int mp[maxn][maxn],dp[maxn],now[maxn];

void dfs(int deep,int x){
    if(deep+dp[x]<=num||deep+n-x+1<=num)return ;
    int able=0;
    int tnow[maxn];
    for(int i=x;i<=n;i++){
        tnow[i]=now[i];
        if(now[i])able++;
    }
    if(able+deep<=num)return ;

    for(int i=x;i<=n;i++){
        if(!tnow[i])continue;
        if(dp[i]+deep<=num)return ;
        for(int j=x;j<=n;j++)
            now[j]=tnow[j]&mp[i][j];
        dfs(deep+1,i);
    }
    if(deep>num)num=deep;
}

int max_Tuan(){
    dp[n]=num=1;
    for(int i=n-1;i>=1;i--){
        for(int j=1;j<=n;j++)now[j]=mp[i][j];
        dfs(1,i+1);
        dp[i]=num;
    }
    return num;
}

int main()
{
    while(~scanf("%d",&n),n){
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&mp[i][j]);
        printf("%d\n",max_Tuan());
    }
    return 0;
}