HDU 6090 计算权值 思维题

来源:互联网 发布:文本压缩算法 编辑:程序博客网 时间:2024/06/05 14:32

Rikka with Graph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 193    Accepted Submission(s): 120


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=1nj=1dist(i,j).

Now, Yuta has n nodes, and he wants to choose no more than m pairs of nodes (i,j)(ij) 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(1t10), the number of the testcases. 

For each testcase, the first line contains two numbers n,m(1n106,1m1012).
 

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

Sample Input
14 5
 

Sample Output
14
 
题意:给出 n 个点和 m 条边,你可以任意组合成一个图,然后对一个图来说它的值就是每个点到其他点的距离
对于相联通的两个点来说这两个点之间的距离就是他们之间最短的边数,而不联通的两个点之间的距离就等于 n
要你求这个图的最小值
思路:对于这个情况来说,其实花朵形状的图(一个点为中心,其他所有点与它相连)是可以使点之间平均距离最小的图,这样对于中心点来说,到其他所有点的距离都是1,其他点到中心的距离是1,到其他点距离是2。
对于 n个点来说,需要(n-1)条边来构成这朵花,如果边数多于(n - 1),那么多出来的边只要加进去,就能使两个点之间的距离由2变为1,由于每个点的距离都要算,所以一条路会算两次,所以每多一条边,那么值就会少2
但是当你这个图已经成为完全图的时候(每两个点之间都有边直接相连)那么再多边也不会减少值了,此时的值就是
(n * (n - 1))。
所以总结就是 三种情况 :
1. m >= (n * (n - 1)) / 2 (完全图)的时候 ans = (n * (n - 1))
2. m > (n - 1) && m < (n * (n - 1)) / 2 的时候,能构成花朵,但不是完全图
ans = (n - 1) * (2 * (n - 2) + 1) + (n - 1) - 2 * (m - n + 1);
3 m < (n - 1) 有一些点可以去加入这朵花,剩下的点只能独立
ans = m * (2 * (m - 1) + 1) + m;
ans += (n - m - 1) * (n - 1) * n + (n - m - 1) * (m + 1) * n;
#include<stdio.h>#define ll long longll tot(int n){return (n * (n - 1)) / 2;} int main(){ll t,n,m;ll ans;scanf("%lld",&t);while(t--){scanf("%lld %lld",&n,&m);if((n * (n - 1)) / 2 <= m){ans = n * (n - 1);}else{if(m >= n - 1){ans = (n - 1) * (2 * (n - 2) + 1) + (n - 1) - 2 * (m - n + 1);}else{ans = m * (2 * (m - 1) + 1) + m;ans += (n - m - 1) * (n - 1) * n + (n - m - 1) * (m + 1) * n;}}printf("%lld\n",ans);}return 0;}