2017ACM暑期多校联合训练 - Team 5 1006 HDU 5205 Rikka with Graph (找规律)

题目链接

Problem Description

As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

For an undirected graph G with n nodes and m edges, we can define the distance between (i,j) (dist(i,j)) as the length of the shortest path between i and j. The length of a path is equal to the number of the edges on it. Specially, if there are no path between i and j, we make dist(i,j) equal to n.

Then, we can define the weight of the graph G (wG) as ∑ni=1∑nj=1dist(i,j).

Now, Yuta has n nodes, and he wants to choose no more than m pairs of nodes (i,j)(i≠j) and then link edges between each pair. In this way, he can get an undirected graph G with n nodes and no more than m edges.

Yuta wants to know the minimal value of wG.

It is too difficult for Rikka. Can you help her?

In the sample, Yuta can choose (1,2),(1,4),(2,4),(2,3),(3,4).

Input

The first line contains a number t(1≤t≤10), the number of the testcases.

For each testcase, the first line contains two numbers n,m(1≤n≤106,1≤m≤1012).

Output

For each testcase, print a single line with a single number -- the answer.

Sample Input

1

4 5

Sample Output

14

题意:

n个点,你可以连接任意<=m条边,得到图G,WG = ∑ ∑ dist(i,j) 其中(ij都是从1到n)

dis(i,j)定义为从i到j经过的边的个数。如果从i无法到达j,则定义为n

问 怎么连边能让WG最小,最小的wg是多少

分析:

1.首先可以确定的一点肯定是边越多越好,这样才能保证尽可能多的两点直接相连,所以在不超过完全图的边的个数情况下,边的条数尽可能大,如果超过达到完全图所需要的边数即m>=n(n-1)/2,那么变成完全图,即答案是n(n-1) ,因为每一条边都要考虑两个方向

2.否则有两种情况(即没有达到完全图的情况)

(1).m>=n-1(相当于能构成一个连通图,任意两点之间可以直接或者间接的到达)

如果图恰好能组成深度为2的树(有一个点为中心(跟节点),直接连接着剩余的n-1个点),那么根节点和剩下n-1个点距离是1,剩余n-1个节点之间都能够通过根节点间接的到达,距离互相都是2,此时这棵树的WG=2*((n-1)+(2*(n-1)*(n-2))/2)

但是我们要考虑没有这么恰好的情况,组成一个连通图用n-1条边,那么剩下m-(n-1)条边当然是连在距离为2的点之间最好,那么此时这棵树的WG=2*( (n-1) + (2*(n-1)*(n-2))/2- (m-(n-1)) ) = 2*(n^2-n-m)

(2).m<n-1 (连通图都构不成,肯定存在不管直接还是间接都无法相连的边)

即无法组成连通图,那么使用m条边,m+1个点按照前一种情况组成一棵树,这棵树的WG1 = 2*(m)^2,余下的点之间都是不通的都是n。组成树的这x个点和其余n-x个点距离和是 WG2=2*n*(m+1)*(n-m-1),,未组成树的n-x个点和除自己之外每个点距离和是WG3=n*(n-m-1)*(n-m-2),故WG =WG1+WG2+WG3

代码:

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
ll n, m;
int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%lld%Illd",&n,&m);
ll ans = 0;
if(m>=(n*(n-1))/2) ans = n*(n-1);///n个点的胡话,最多连接(n*(n-1))/2条边就能保证任意的两个点直接相连
else if (m >= n-1)
{
ans = 2*(n*n - n - m);
}
else
{
ans= 2*m*m+(n-m-1)*(m+1)*n*2+(n-m-1)*(n-m-2)*n;
}
printf("%lld\n",ans);
}
return 0;
}
上一篇:HDU 5631 Rikka with Graph 暴力 并查集


下一篇:HDU 6090 Rikka with Graph —— 2017 Multi-University Training 5