E - Rikka with Graph
HDU - 6090
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 GG with nn nodes and mm edges, we can define the distance between (i,j)(i,j) (dist(i,j)dist(i,j)) as the length of the shortest path between ii and jj. The length of a path is equal to the number of the edges on it. Specially, if there are no path between ii and jj, we make dist(i,j)dist(i,j) equal to nn.
Then, we can define the weight of the graph GG (wGwG) as ∑ni=1∑nj=1dist(i,j)∑i=1n∑j=1ndist(i,j).
Now, Yuta has nn nodes, and he wants to choose no more than mm pairs of nodes (i,j)(i≠j)(i,j)(i≠j) and then link edges between each pair. In this way, he can get an undirected graph GG with nn nodes and no more than mm edges.
Yuta wants to know the minimal value of wGwG.
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)(1,2),(1,4),(2,4),(2,3),(3,4).
Input
The first line contains a number t(1≤t≤10)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)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條邊,連接成一個圖,如果兩個結點連通,那么距離為這兩個結點之間的邊的數量,如果不連通,距離為n,求所有節(jié)點與其他結點距離之和
解法:分情況討論,m>=n(n-1)/2,n(n-1)/2m>=n-1,m<n-1
代碼:
#include<iostream>
using namespace std;
int main()
{
long long num,n,m;
cin>>num;
while(num--){
cin>>n>>m;
if(m>=(n-1)*n/2)
cout<<n*(n-1)<<endl;
else if(m>=n-1)
cout<<2*n*(n-1)-2*m<<endl;
else
cout<<(2*(m-1)+1+(n-m-1)*n)*m+m+n*(n-m-1)+n*(n-1)*(n-m-1)<<endl;
}
return 0;
}