HDU-6184-Counting Stars(广西邀请赛C题)(数据结构优化)

题目链接

题意:给你一张图,然后问你有多少个A-数据结构具体结构就是一个正方形里面加一条线。

思路:就是求出所有的三元环,然后组合一下。具体想法就是,对于每一条边,然后求出有多少个点能和这条边组成三角形。然后组合一下就好了。

具体操作:直接枚举边,然后再去枚举每个端点,我先这么枚举了一下,发现不行,T了。然后我们就可以换一种角度,去枚举每一个点,然后在去枚举每一条河这个点有关的边,如果这个点被枚举过了,就可以不用枚举了,这样省下了很多时间。另外这里还用了一个小操作,很骚。就是对于判断一条边是不是存在,可以直接手动把这条边给hash了。具体看代码。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>

#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>

using namespace std;

#define pb push_back
#define pi acos(-1)

const long long mod = 1000000007;

#define maxn 111111
#define maxm 11111
vector<int> gg[maxn];
int vis[maxn];
int nex[maxn];
int out[maxn];
int n, m;
set<long long> ss;
int main()
{

    long long ans, tot;
    int limt;
    while(scanf("%d%d", &n, &m) != EOF) {
        int limt = sqrt(m);
        ss.clear();
        for(int i = 1; i <= n; i++) {
            gg[i].clear();
            vis[i] = out[i] = nex[i] = 0; //清空所有
        }
        int x, y;
        for(int i = 1; i <= m; i++) {
            scanf("%d%d" , &x, &y);
            gg[x].pb(y); //放入边
            gg[y].pb(x);
            out[x]++;
            out[y]++;
            ss.insert((long long)x * n + y);  //hash边
            ss.insert((long long)y * n + x);
        }
        ans  = 0;
        int xx, yy, zz;
        for(int i = 1; i <= n; i++) {
            xx = i;
            vis[xx] = 1;
            for(int j = 0; j < gg[xx].size(); j++) 
                nex[gg[xx][j]] = xx;   //nex数组是一个可持续化的数组,可以用来储存当前点所连点边
            for(int j = 0; j < gg[xx].size(); j++) {
                tot = 0;
                yy = gg[xx][j];
                if(vis[yy]) continue;
                if(out[yy] <= limt) { // 如果yy点所连点边超过log(m)就暴力枚举,如果超过就用set优化
                    for(int k = 0; k < gg[yy].size(); k++) {
                        zz = gg[yy][k];
                        if(nex[zz] == xx) tot++;
                    }
                }
                else {
                    for(int k = 0; k < gg[xx].size(); k++) {
                        zz = gg[xx][k];
                        if(ss.find((long long) zz * n + yy) != ss.end()) tot++;   //set优化
                    }
                }
                ans += tot * (tot - 1) / 2;
            }

        }
        printf("%lld\n", ans);

    }

    return 0;
}














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值