Friendships(思维)

题目描述
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值