Codeforces Round #142 (Div. 2) E. Triangles

来源:互联网 发布:wpf windows边框样式 编辑:程序博客网 时间:2024/04/29 18:40


E. Triangles
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with n vertices, chooses some m edges and keeps them. Bob gets the remaining edges.

Alice and Bob are fond of "triangles" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly?

Input

The first line contains two space-separated integers n and m (1 ≤ n ≤ 106, 0 ≤ m ≤ 106) — the number of vertices in the initial complete graph and the number of edges in Alice's graph, correspondingly. Then m lines follow: the i-th line contains two space-separated integers aibi (1 ≤ ai, bi ≤ nai ≠ bi), — the numbers of the two vertices connected by the i-th edge in Alice's graph. It is guaranteed that Alice's graph contains no multiple edges and self-loops. It is guaranteed that the initial complete graph also contains no multiple edges and self-loops.

Consider the graph vertices to be indexed in some way from 1 to n.

Output

Print a single number — the total number of cycles of length 3 in Alice and Bob's graphs together.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cincout streams or the %I64dspecifier.

Sample test(s)
input
5 51 21 32 32 43 4
output
3
input
5 31 22 31 3
output
4
Note

In the first sample Alice has 2 triangles: (1, 2, 3) and (2, 3, 4). Bob's graph has only 1 triangle : (1, 4, 5). That's why the two graphs in total contain 3 triangles.

In the second sample Alice's graph has only one triangle: (1, 2, 3). Bob's graph has three triangles: (1, 4, 5), (2, 4, 5) and (3, 4, 5). In this case the answer to the problem is 4.


题目大意:一个无向完全图,拆成两部分,问这两部分一共有多少三角形。

  完全图中共有C(n,3)个三角形,对于某个点x,如果有deg[x]个点与x相连,那么剩下(n-x-1)个点就不与x相连了,于是就减少了deg[x]*(n-deg[x]-1)个包含x的三角形(乘法原理)。然后每个点计算了两遍,再除以2即可。

代码:

#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<cstdio>using namespace std;int n,m,t,i,j,k;long long a[2000005];long long ans,sum;int main(){ scanf("%d%d",&n,&m);  for(i=1;i<=m*2;i++)    {        scanf("%d",&t);        a[t]++;    }  for(i=1;i<=n;i++)    ans+=a[i]*(n-1-a[i]);printf("%lld\n",(long long)n*(n-1)*(n-2)/6-ans/2);   return 0;}

0 0
原创粉丝点击