首页 > 代码库 > CodeForces 489D Unbearable Controversy of Being

CodeForces 489D Unbearable Controversy of Being

题意:

n(3000)个点m(30000)条边的有向简单图  统计题目中所画的菱形数目

思路:

我们将菱形可以看作a->c点距离为2的两条路  那么假设我们枚举i j两点同时知道i->j距离为2的路径条数  就可以用简单的组合数计算

如果暴力计算路径条数则是n^3的  不过我们可以利用距离为2这个特点  我们同时用邻接表和邻接矩阵存储图  通过邻接表枚举所有边m  这时知道i->k距离为1  那么我们再枚举所有n个点  邻接矩阵判断如果k->j有路  则i->j有长度2的路径  复杂度为O(nm)

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<bitset>
using namespace std;
#define N 3010
typedef long long LL;

int n, m;
LL ans;
vector<int> ed[N];
int maz[N][N], f[N][N];

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++) {
        int u, v;
        scanf("%d%d", &u, &v);
        maz[u][v] = 1;
        ed[u].push_back(v);
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < ed[i].size(); j++) {
            for (int k = 1; k <= n; k++) {
                if (maz[ed[i][j]][k])
                    f[i][k]++;
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i != j && f[i][j] > 1)
                ans += (LL) (f[i][j] - 1) * f[i][j] / 2;
            //printf("%d %d %d\n", i, j, f[i][j]);
        }
    }
    printf("%I64d\n", ans);
    return 0;
}


CodeForces 489D Unbearable Controversy of Being