A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.
Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
The first line consists of two integers n and m
.
Then m lines follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n.
It is guaranteed that every pair of cities will appear at most once in the input.
You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that a road should be constructed between cities ai and bi.
If there are several solutions, you may print any of them.
4 1
1 3
3
1 2
4 2
2 3
This is one possible solution of the example:

These are examples of wrong solutions:



题目大意:
输入两个数n,m;再输入m对整数,城市的编码是从1到n。找一个点,使得它能够与其他所有点都相连。
解题思路:
通过观察数据,可以得出一个重要结论:n/2>m, 意味着必存在一个点可以与其他点相连。那么最重要的就是寻找那个点。
代码实现:
-
#include <iostream>
- #include <algorithm>
- #include <cstdio>
- #include <cstdlib>
- #include <cmath>
- #include <cstring>
-
#include <string>
- using namespace std;
-
int a[10010];
- int main()
- {
- int n,m,x,y,i,cnt;
- scanf("%d %d",&n,&m);
- for(i=0;i<m;i++)
- {
- scanf("%d %d",&x,&y);
-
a[x]++;
//把出现的数对作为数组a的下标,记录存在
- a[y]++;
- }
- for(i=1;i<=n;i++)
- {
-
if(a[i]<1)
//寻找那个公共点cnt
- {
- cnt=i;
- break;
- }
- }
- printf("%d\n",n-1);
- for(i=1;i<=n;i++)
- {
- if(i!=cnt)
- {
-
printf("%d %d\n",i,cnt);
//依次输出与公共点相连的点
- }
- }
- return 0;
-
}
解决一个国王希望在国家中建设最少数量的道路,使得任意两城市间可通过至多两条道路相连的问题,同时避免某些特定道路组合。
260

被折叠的 条评论
为什么被折叠?



