您的位置:首页 > 理论基础 > 数据结构算法

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

2017-09-15 22:15 381 查看

题目链接

题意:给你一张图,然后问你有多少个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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 hash