Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Problem Description
There are n stones numbered from 1 to n.
The weight of the i-th stone is i kilograms. We divide the stones into k groups.
Each group consists of exactly stones.
We define the weight of each group is sum of the stones’ weights in the group.
Can we divide the stones so that the weights of all groups are same?Input
The first line of input contains an integer T (1 <= T <= 100) denoting the number of test cases.
Each test case consists of one line containing two integers n (1 ≤ n ≤ 100000), k (k is divisor of n).
It is guaranteed that the sum of n overall test cases does not exceed 500000.Output
For each test case, if you can’t divide into k groups satisfying condition, print “no”.
Else if you can divide into k groups satisfying condition, print “yes” in one line and then print k lines.
The i-th line represent the indices of stones belonging to the i-th group.
If there are multiple solutions, you can print any of them.Sample Input
1
4 2
Sample Output
yes
1 4
2 3
题意:
将1~n这n个数分为和相等的k部分
分析:
先特判一些显然的情况(虽然我已经死在特判上一万次但我还是要特判):
k==1时,答案是yes和1~n;
n==k && k!=1时 答案是no;
1~n的和不能整除k时 答案是no;
然后来看一般的情况:
n/k为偶数时,答案就是头+尾这样,很简单;
n/k为奇数时,可以先将前3k项分为相等的k份,然后剩下的再头+尾;
#include<bits/stdc++.h>
#define pb push_back
#define ll long long
using namespace std;
const int maxn=1e5+7;
vector<int> ans[maxn];
int n,k;
void rua()
{
scanf("%d%d",&n,&k);
if(k==1)
{
printf("yes\n");
for (int i=1;i<n;i++) printf("%d ",i);
printf("%d\n",n);
return;
}
if(n==k) {printf("no\n");return;}
ll sum=1ll*n*(1+n)/2;
if(sum%k!=0) {printf("no\n");return;}
int tmp=n/k;
printf("yes\n");
if(tmp%2==0)
{
tmp/=2;//tmp组 头+尾
int res=1;
for (int i=1;i<=k;i++)
for (int j=1;j<=tmp;j++) {ans[i].pb(res);ans[i].pb(n-res+1);res++;}
}
else if(tmp%2==1)
{
ll num=1ll*3*(3*k+1)/2;
for (int i=1;i<=k;i++) ans[i].pb(i);
int tt=k+1;
for (int i=k;i>0;i-=2) ans[i].pb(tt),tt++;
for (int i=k-1;i>0;i-=2) ans[i].pb(tt),tt++;
for (int i=1;i<=k;i++) ans[i].pb(num-ans[i][0]-ans[i][1]);
int kk=(tmp-3)/2,res=1;
for (int i=1;i<=k;i++)
for (int j=1;j<=kk;j++) {ans[i].pb(3*k+res);ans[i].pb(n-res+1);res++;}
}
for (int i=1;i<=k;i++)
{
for (int j=0;j<ans[i].size()-1;j++) printf("%d ",ans[i][j]);
printf("%d\n",ans[i][ans[i].size()-1]);
}
for (int i=0;i<=k;i++) ans[i].clear();
return;
}
int main()
{
int t;scanf("%d",&t);
while (t--) rua();
return 0;
}