zoukankan      html  css  js  c++  java
  • UVALive 7616 Counting Cliques【DFS回溯】

    题意:

    给一个无向图,求有多少个大小为S的团。

    题解:

    回溯+dfs。

    连边时,编号小的节点向编号大的节点连边。这样每个团恰被枚举一次!

     code: 

    #include <iostream>
    #include <vector>
    using namespace std;
    #define N 102
    int T, n, m, s, ans;
    int u, v, a[N], cnt, vis[N];
    int has[N][N];
    vector<int> G[N];
    bool valid(int x) {
        for (int i = 1; i <= cnt; i ++) {
            if (!has[a[i]][ x ]) return 0;
        }
        return 1;
    }
    void dfs(int u) {
        if (cnt == s) {ans ++; return;}
        for (int i = 0; i < G[u].size(); i ++) {
            int v = G[u][i];
            if (valid(v)) {
                a[++cnt] = v;
                dfs(v);
                cnt --;
            }
        }
    }
    int main() {
        scanf("%d", &T);
        while (T --) {
            scanf("%d %d %d", &n, &m, &s);    
            ans = 0;
            for (int i = 1; i <= n; i ++) {
                G[i].clear(); for (int j = 1; j <= n; j ++) has[i][j] = 0;
            }
            for (int i = 1; i <= m; i ++) {
                scanf("%d %d", &u, &v);
                if (u > v) swap(u, v);
                G[u].push_back(v);
                has[u][v] = 1;
            }
            for (int i = 1; i <= n; i ++) {
                cnt = 1, a[cnt] = i;
                dfs(i);
            }
            printf("%d
    ", ans);
        }
    }
    

      

  • 相关阅读:
    322. Coin Change
    368.[LeetCode] Largest Divisible Subset
    c++
    python 循环
    2018今日头条
    c++中set的用法
    [LeetCode]48. Rotate Image 旋转图片
    [LeetCode]47. Permutations II
    [LeetCode]46. Permutations
    sys与os模块(转载)
  • 原文地址:https://www.cnblogs.com/RUSH-D-CAT/p/7675349.html
Copyright © 2011-2022 走看看