Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
3 2
2 1 2 2 3
5 3
3 1 2 2 3 3 4 3 5
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
题意:给出n个点,要求这些点组成的图中,度数为1的点有k个,度数为1的点为入口或出口,求组成的图中从入口到出口最长的路的最短距离。
思路:
如图,假设n为6,k为3
以中间点3为中心先连接k个点:2,4,6,然后再这3个点上再各连接1个点,以这样的方法扩散,可以保证连接出的图最长路最短。
如果遇到像图中点不够的情况,那么最长路便是1——5。具体计算方法看代码吧!
#include<stdio.h>
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
int mod,ans,t,p,a;
mod=(n-1)%k;//看围不成一周时剩余几个点。
t=(n-1)/k;//正常围成一圈,一个分支的长度
if(mod>=2)
ans=2*t+2;//如果剩下的点大于2,那么每一个分支加一点,最长路长度就增加2
else
ans=2*t+mod;
p=(k-1)-mod;//k-mod是算出没有另外连接点的分支,因为要先输出一段正常路,所以多减1
printf("%d\n",ans);
int i=1,j;//下面就是输出路径了,我的思路是先从入口到中心,然后从中心扩散,先输出正常路,再输出多点路
for(j=0;j<t;j++)
{
printf("%d %d\n",i,i+1);
i++;
}
a=i;
while(p--)
{
i++;
printf("%d %d\n",a,i);
for(j=0;j<t-1;j++)
{
printf("%d %d\n",i,i+1);
i++;
}
}
while(mod--)
{
i++;
printf("%d %d\n",a,i);
for(j=0;j<t;j++)
{
printf("%d %d\n",i,i+1);
i++;
}
}
}
}