Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols “0” and “1”). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to “1”.
More formally, f(s) is equal to the number of pairs of integers (l,r), such that 1≤l≤r≤|s| (where |s| is equal to the length of string s), such that at least one of the symbols sl,sl+1,…,sr is equal to “1”.
For example, if s=“01010” then f(s)=12, because there are 12 such pairs (l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to “1”, find the maximum value of f(s).
Mahmoud couldn’t solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1≤t≤10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1≤n≤10^9, 0≤m≤n) — the length of the string and the number of symbols equal to “1” in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to “1”.
样例:
输入
5
3 1
3 2
3 3
4 0
5 2
输出:
4
5
6
0
12
题意:
给定长度为n,含m个 ‘1’ 的二进制字符串,问含 ‘1’ 的子串个数最多能有多少个?
思路:
思维题,组合数学知识。求出公式O(1)解决即可。
子串中至少含有一个1,用总的子串个数sum=(n+1)*n/2减去全 0 的子串个数。字符串全0全1的两种情况好求,可以发现间隔的0,eg:‘010’比相邻的0,‘000’所含0的子串个数要少,所以要用 ‘1’ 把 ‘0’ 隔开,m个1最多能隔开m+1组0。在思考过程中当m=0 或者 m=n或者0的个数小于1的个数的情况都包含在公式里了,所以不用特判了,需注意的是两大数相乘,开long long。
#include
using namespace std;
typedef long long ll;
int main()
{
int t;
cin >> t;
ll n,m;
while(t--)
{
scanf("%lld %lld",&n,&m);
ll sum = n * ( n + 1 ) / 2;//总的子串个数
ll oo = n - m; //0的个数
ll a = oo / ( m + 1 ); //把0分成m+1组,每组至少有0的个数
ll b = oo % ( m + 1 ); //多余的0,m+1组中还有b组能多1个0
ll ans = sum - b * ( a + 1 ) * ( a + 2 ) / 2 - ( m + 1 - b) * a * ( a + 1 )/2;
printf("%lld\n",ans);
}
return 0;
}