[codeforces] C. Jamie and Interesting Graph
题目:
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
The graph of sample 1:Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 ≤ i < k and the sum of weight is minimized where w(i, j) is the edge weight between i and j. (https://en.wikipedia.org/wiki/Shortest_path_problem)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (https://en.wikipedia.org/wiki/Prime_number)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (https://en.wikipedia.org/wiki/Minimum_spanning_tree)
代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
using namespace std;
const int N=3e5+9;
int prime[N];
bool is_prime[N];
int tot=0;
void get_prime()
{
mem(is_prime,true);
is_prime[0]=is_prime[1]=false;
for(int i=2; i<N; i++)
{
if(is_prime[i])
{
prime[tot++]=i;
for(int j=2*i; j<=N; j+=i)
is_prime[j]=false;
}
}
}
int main()
{
get_prime();
int n,m;
scanf("%d%d",&n,&m);
int num=prime[lower_bound(prime,prime+tot,n-1)-prime];
int cha=num-n+1;
int t=m-n+1;
printf("%d %d\n",num,num);
for(int i=1; i<=n-1; i++)
{
if(i==1)
printf("%d %d %d\n",i,i+1,cha+1);
else
printf("%d %d %d\n",i,i+1,1);
}
for(int i=1; i<=n-1; i++)
{
for(int j=i+2; j<=n; j++)
{
if(t==0) return 0;
t--;
printf("%d %d %d\n",i,j,10000000);
}
}
return 0;
}
结果:
上一篇: 外部中断,定时器中断,PWM
下一篇: java数据结构和算法之马踏棋盘算法