题目描述
Does there exist an undirected graph with N vertices satisfying the following conditions?
The graph is simple and connected.
The vertices are numbered 1,2,…,N.
Let M be the number of edges in the graph. The edges are numbered 1,2,…,M, the length of each edge is 1, and Edge i connects Vertex ui and Vertex vi.There are exactly K pairs of vertices (i, j) (i<j) such that the shortest distance between them is 2.
If there exists such a graph, construct an example.
Constraints
·All values in input are integers.
·2≤N≤100
·0≤K≤N(N−1)/2
输入
Input is given from Standard Input in the following format:
N K
输出
If there does not exist an undirected graph with N vertices satisfying the conditions, print -1.
If there exists such a graph, print an example in the following format (refer to Problem Statement for what the symbols stand for):
M
u1 v1
:
uM vM
If there exist multiple graphs satisfying the conditions, any of them will be accepted.
样例输入
【样例1】
5 3
【样例2】
5 8
样例输出
【样例1】
5
4 3
1 2
3 1
4 5
2 3
【样例2】
-1
提示
样例1解释:This graph has three pairs of vertices such that the shortest distance between them is
2: (1, 4), (2, 4), and (3, 5). Thus, the condition is satisfied.
样例2解释:There is no graph satisfying the conditions.
思路
对于一个图,要使两点之间最短距离为2,最简单的构造方法是n-1个点全部连接在一个点上,因此答案最多为(n-1)*(n-2)/2种,若k>(n-1)*(n-2)/2,则无解,因为要恰好k个,可以发现将除中心点外的两点连接在一起会使种类数量-1,因此直接输出n-1+(n-1)*(n-2)/2-k条路即可
代码实现
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N=2005;
const int M=10005;
const int INF=0x3f3f3f;
const ull sed=31;
const ll mod=1e9+7;
const double eps=1e-9;
typedef pair<int,int>P;
typedef pair<double,double>Pd;
int n,k;
int main()
{
scanf("%d%d",&n,&k);
int sum=(n-1)*(n-2)/2;
if(k>sum)
{
puts("-1");
return 0;
}
int cnt=n-1+sum-k;
printf("%d\n",cnt);
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
cnt--;
printf("%d %d\n",i,j);
if(!cnt) break;
}
}
return 0;
}