Jamie has recently found undirected weighted graphs with the following properties very interesting:
- The graph is connected and contains exactly n vertices and m edges.
- All edge weights are integers and are in range [1, 109] inclusive.
- The length of shortest path from 1 to n is a prime number.
- The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
- The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
First line of input contains 2 integers n, m — the required number of vertices and edges.
In the first line output 2 integers sp, mstw (1 ≤ sp, mstw ≤ 1014) — the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 ≤ u, v ≤ n, 1 ≤ w ≤ 109) describing the edge connecting u and v and having weight w.
4 4
7 7 1 2 3 2 3 2 3 4 2 2 4 4
5 4
7 13 1 2 2 1 3 4 1 4 3 4 5 4
题意:给定点数与边数,要求构造一个图,满足图中1到n的最短路与最小生成树的权值均为质数。
思路:不妨先构造出这个图的最短路,构造一条链,使得前n-2条边的权值为1,最后一条边将最短路的权值凑成一个质数。再次向图中添加权值尽可能大的边直到满足m条边,则图的最小生成树也为最短路。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int prime = 1e5+3; //任取一个大于1e5的质数
const int maxn = 1e7;
int main()
{
int n,m;
while (~scanf("%d %d",&n,&m)){
printf("%d %d\n",prime,prime);
printf("1 2 %d\n",prime-n+2);
int cnt=m-n+1,f=0;
for (int i=2;i<n;i++){
printf("%d %d 1\n",i,i+1);
}
for (int i=1;i<n-1;i++){
for (int j=i+2;j<=n;j++){
if (cnt==0){
f=1;
break;
}
printf("%d %d %d\n",i,j,maxn);
cnt--;
}
if (f)
break;
}
}
return 0;
}