poj1419Graph Coloring(一般图最大独立集或着最大团)

来源:互联网 发布:逃出克隆岛 知乎 编辑:程序博客网 时间:2024/05/23 21:26

一般图的最大独立集和最大团是等效的。图G = (V, E),其补图G’。G的最大独立集等价于G’的最大团。度娘
一般的做法就是搜索。

// 最大独立集做法vector<vector<int> > G;int n, m;int color[123];vector<int> rec;int maxnum;void dfs(int u,int _count) {    if (_count > maxnum) {//更新答案        maxnum = _count;        rec.clear();        for (int i = 1;i <= n;++i) {            if (color[i]) rec.push_back(i);        }    }    if (u == n + 1) return ;    //用于判断是否可以染成黑色    bool ok = true;    for (int i = 0;i < G[u].size();++i) {        if (color[G[u][i]]) ok = false;    }    if (ok) {//u节点可以染成黑色        color[u] = 1;        dfs(u + 1, _count + 1);        color[u] = 0;    }    dfs(u + 1, _count);//u染成白色->跳过}int main(int argc, const char * argv[]){        // freopen("in.txt","r",stdin);    // freopen("out.txt","w",stdout);    // clock_t _ = clock();    int t, u, v;    cin >> t;    while(t--) {        scanf("%d%d", &n, &m);        G.clear();        G.resize(n + 2);        while(m--) {            scanf("%d%d", &u, &v);            G[u].push_back(v);            G[v].push_back(u);        }        memset(color, 0,sizeof color);        maxnum = 0;        dfs(1, 0);        printf("%d\n", maxnum);        for (int i = 0;i < rec.size();++i)            printf("%d%c", rec[i], i == maxnum - 1?'\n':' ');    }    // printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC);    return 0;}//最大团做法int mp[123][123];int rec[123];int tmp[123];int cnt, ans;int n, m;void dfs(int u) {    if (u == n + 1) {        if (cnt > ans)            ans = cnt;            memcpy(rec, tmp, sizeof tmp);        return ;    }//判断u是否可以划入到这个团中去    bool ok = true;    for (int i = 1;i < u;++i) {        if (tmp[i] && mp[i][u]) {            ok = false;            break;        }    }    if (ok) {        tmp[u] = 1;cnt++;        dfs(u + 1);        tmp[u] = 0;cnt--;    }//跳过u节点后判断下可行性    if (n + cnt - u > ans)         dfs(u + 1);}int main(int argc, const char * argv[]){        // freopen("in.txt","r",stdin);    // freopen("out.txt","w",stdout);    // clock_t _ = clock();    int t;    cin >> t;    while(t--) {        scanf("%d%d", &n, &m);        memset(mp, 0,sizeof mp);        memset(tmp, 0,sizeof tmp);        int u, v;        for (int i = 1;i <= m;++i) {            scanf("%d%d", &u, &v);            mp[u][v] = mp[v][u] = 1;        }        cnt = ans = 0;        dfs(1);        printf("%d\n", ans);        bool first = true;        for (int i = 1;i <= n;++i) {            if (rec[i]) {                if (first) printf("%d", i);                else printf(" %d", i);                first = false;            }        }        printf("\n");    }    // printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC);    return 0;}
0 0
原创粉丝点击