2012年8月24日 星期五

最大團問題- Clique

wikepedia
(clique)是圖論中的用語。對於給定G=(V,E)。其中,V={1,…,n}是圖G的頂點集,E是圖G的集。圖G的團就是一個兩兩之間有邊的頂點集合。如果一個團不被其他任一團所包含,即它不是其他任一團的真子集,則稱該團為圖G的極大團(maximal clique)。頂點最多的極大團,稱之為圖G的最大團(maximum clique)。最大團問題的目標就是要找到給定圖的最大團。
dynamic programming解:
//reference: ACM/ICPC代碼庫  http://ir.hit.edu.cn/~lfwang/docs/MyLib(For%20ACM).pdf
#include<stdio.h>
#include<iostream>
#include<vector>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define V 100               //maximum point

using namespace std;

int g[V][V], dp[V], stk[V][V], mx;
int dfs(int n, int ns, int dep){
    if (0 == ns) {
        if (dep > mx) mx = dep;
        return 1;
    }
    int i, j, k, p, cnt;
    for (i = 0; i < ns; i++) {
        k = stk[dep][i]; cnt = 0;
        //if (dep + n - k <= mx) return 0;
        if (dep + dp[k] <= mx) return 0;
        for (j = i + 1; j < ns; j++) {
            p = stk[dep][j];
            if (g[k][p]) stk[dep + 1][cnt++] = p;
        }
        dfs(n, cnt, dep + 1);
    }
    return 1;
}
int clique(int n){
    int i, j, ns;
        for (mx = 0, i = n - 1; i >= 0; i--) {
        // vertex: 0 ~ n-1
            for (ns = 0, j = i + 1; j < n; j++)
                if (g[i][j]) stk[1][ ns++ ] = j;
            dfs(n, ns, 1);
            dp[i] = mx;
        }
    return mx;
}
int main(){
    int N,M,a,b,res;        //N是點數,M是邊數
    cin>>N>>M;              
    for(int i=0;i<b;i++)cin>>a>>b,g[a][b]=1,g[b][a]=1;
    res=clique(N);
    printf("%d\n",res);
}

沒有留言:

張貼留言