【HDU6184】Counting Stars(三元环计数)

Description

https://vjudge.net/problem/HDU-6184


Solution

参考:https://www.cnblogs.com/Mychael/p/9090006.html

无向图三元环计数问题。

对于每一条无向边,只连从度数小的点到度数大的点的有向边(如果度数相等则从编号小的连向标号大的)。
然后对于每一条边 ( u , v ) ,找出与 u 相连的点并标记,再找出与 v 相连的点,如果该点被标记过的,那么就找到了一个三元环。
时间复杂度 O ( m m )

这道题的话,算出每条边可以作为多少个三元环的一边,用 ( x 2 ) 算即可。


Code

/************************************************ * Au: Hany01 * Date: Jun 25th, 2018 * Prob: HDU6184 * Email: hany01@foxmail.com * Institute: Yali High School ************************************************/

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
#define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
#define rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define x first
#define y second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) ((int)(a).size())
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia

template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }

inline int read()
{
    register int _, __; register char c_;
    for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
    for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
    return _ * __;
}

const int maxn = 300005, maxm = 600005;

int n, m, e, beg[maxn], v[maxm], nex[maxm], deg[maxn], cnt[maxm], co[maxn], en[maxn], tim;
PII E[maxm];
LL Ans;

inline void add(int uu, int vv) { v[++ e] = vv, nex[e] = beg[uu], beg[uu] = e; }

int main()
{
#ifdef hany01
    File("hdu6184");
#endif

    while (scanf("%d%d", &n, &m) != EOF) {
        Set(beg, 0), Set(deg, 0), e = 0, Set(en, 0), Set(co, 0), Set(cnt, 0), Ans = 0;
        For(i, 1, m) ++ deg[E[i].x = read()], ++ deg[E[i].y = read()];
        For(i, 1, m) {
            if (deg[E[i].x] > deg[E[i].y] || (deg[E[i].x] == deg[E[i].y] && E[i].y > E[i].x)) swap(E[i].x, E[i].y);
            add(E[i].x, E[i].y);
        }
        For(i, 1, m) {
            int x = E[i].x, y = E[i].y;
            ++ tim;
            for (register int j = beg[x]; j; j = nex[j])
                co[v[j]] = tim, en[v[j]] = j;
            for (register int j = beg[y]; j; j = nex[j]) if (co[v[j]] == tim)
                ++ cnt[j], ++ cnt[i], ++ cnt[en[v[j]]];
        }
        For(i, 1, m) Ans += (LL)(cnt[i] - 1) * cnt[i] / 2;
        cout << Ans << endl;
    }

    return 0;
}
//过眼年华,动人幽意,相逢几番春换。
// -- 王沂孙《法曲献仙音·聚景亭梅次草窗韵》
相关文章
相关标签/搜索