hdoj 5952 Counting Cliques

来源:互联网 发布:上海数据交易中心工资 编辑:程序博客网 时间:2024/05/29 15:10

题目链接:Counting Cliques

题目大意:给你一张n个点,m条边的无向图,问尺寸为s的完全图有多少个,尺寸即为这张完全图有多少个点,完全图是值每两点之间都有边

题目思路:这题吃时间吃的比较紧,想法还是很简单,从某一个点开始dfs,然后每次去dfs与他相连的边,然后如果这个边与之前已经存在完全图里面的边都相连的话(这个用邻接矩阵去判断),这道题最主要的地方是优化,我们可以从1开始遍历比他大的点,2也遍历比它大的点,然后遍历的时候不用去遍历所有点,只遍历与它相连并且编号比他大的点(这个是主要优化),然后还可以有很多的小优化,都写在代码里面了

#include <map>#include <set>#include <queue>#include <stack>#include <cmath>#include <vector>#include <cstdio>#include <cstring>#include <cstdlib>#include <iostream>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 105;int matrix[maxn][maxn],t,n,m,s;int que[15],cot,num,degree[maxn];vector<int>vec[maxn];template <class T>inline bool scan_d(T &ret){    char c;    int sgn;    if (c = getchar(), c == EOF)    {        return 0; //EOF    }    while (c != '-' && (c < '0' || c > '9'))    {        c = getchar();    }    sgn = (c == '-') ? -1 : 1;    ret = (c == '-') ? 0 : (c - '0');    while (c = getchar(), c >= '0' && c <= '9')    {        ret = ret * 10 + (c - '0');    }    ret *= sgn;    return 1;}bool check(int x){    if(degree[x] < s-1) return false;    for(int i = 0;i < cot;i++){        if(matrix[x][que[i]] == 0) return false;    }    return true;}void dfs(int x){//    for(int i = 0;i < cot;i++)//        cout<<que[i]<<" ";//    cout<<endl;    if(s-cot > n-x) return ;    if(cot == s){        num++;        return ;    }    for(int i = 0;i < vec[x].size();i++){        if(check(vec[x][i])){            que[cot++] = vec[x][i];            dfs(vec[x][i]);            cot--;        }    }}int main(){    //scan_d(t);    scanf("%d",&t);    while(t--){        //scan_d(n);scan_d(m);scan_d(s);        scanf("%d",&n);scanf("%d",&m);scanf("%d",&s);        for(int i = 1;i <= 100;i++) vec[i].clear();        cot = 0;        num = 0;        memset(matrix,0,sizeof(matrix));        memset(degree,0,sizeof(degree));        while(m--){            int u,v;            scan_d(u);scan_d(v);            matrix[u][v] = matrix[v][u] = 1;            degree[u]++;            degree[v]++;            if(v > u) vec[u].push_back(v);            else vec[v].push_back(u);        }        for(int i = 1;i <= n-s+1;i++){                if(degree[i] < s-1) continue;                que[cot++] = i;                dfs(i);                cot--;        }        printf("%d\n",num);    }    return 0;}
原创粉丝点击