A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
题意:有 n 个学校标号为 1 ~ n ,当任意 i 和 j 满足 1 <= i , j <= n,则 i 和 j 之间旅行票价的费用为 (i+j)%(n+1) ,每组 (i,j) 间的票只要购买就可以重复使用。问访问所有学校最小需要多少钱买票。
票可以重复使用就是说明一旦买过两点之间的票,它们就是始终连接的,其实就是一个类似并查集的东西。首先 (i+j)=(n+1),这些 (i,j) 点对的票价是 0,所以它们本身就连通,即一开始我们就有 (n+1)/2 个并查集了,这是无花费的,而剩余所有边都是有花费的。对于 k 个并查集,至少需要 (k-1) 条边使其全部连通,类似最小生成树。那么我们考虑 (i+j)=(n+2),发现所有 (n+1)/2 个并查集可以通过这些费用为 1 的边全部连通,正好 (n+1)/2-1 条这样的边。因此花费就是 (n+1)/2-1,并且一定最小。
1 #include <stdio.h>
2 #include <string.h>
3 #include <algorithm>
4 #include <math.h>
5 using namespace std;
6
7 const int maxn = 1e5 + 5;
8 const int mod = 1e9 + 7;
9 const int INF = 0x3f3f3f3f;
10 const double eps = 1e-8;
11
12 int main(){
13 int n;
14 scanf("%d",&n);
15 int num=(n+1)/2;
16 printf("%d
",num-1);
17 return 0;
18 }