BZOJ3714: [PA2014]Kuglarz

3714: [PA2014]Kuglarz

Time Limit: 20 Sec  Memory Limit: 128 MB
Submit: 835  Solved: 463
[Submit][Status][Discuss]

Description

魔术师的桌子上有n个杯子排成一行,编号为1,2,…,n,其中某些杯子底下藏有一个小球,如果你准确地猜出是哪些杯子,你就可以获得奖品。花费c_ij元,魔术师就会告诉你杯子i,i+1,…,j底下藏有球的总数的奇偶性。
采取最优的询问策略,你至少需要花费多少元,才能保证猜出哪些杯子底下藏着球?

Input

第一行一个整数n(1<=n<=2000)。
第i+1行(1<=i<=n)有n+1-i个整数,表示每一种询问所需的花费。其中c_ij(对区间[i,j]进行询问的费用,1<=i<=j<=n,1<=c_ij<=10^9)为第i+1行第j+1-i个数。

Output

输出一个整数,表示最少花费。

Sample Input

5
1 2 3 4 5
4 3 2 1
3 4 5
2 1
5

Sample Output

7

HINT

Source

【题解】

“问题等价于确定每个杯子中球的个数的奇偶性
令 s[i] 表示杯子 1 ~ i 中的球个数总和
一次询问 (i, j),我们获得的信息实际上是 s[i-1] 和 s[j] 是否同奇偶
如果知道 s[i] 与 s[j] 的关系,和 s[j] 与 s[k] 的关系,可以推出 s[i] 和 s[k] 的关系
想知道是否每个杯子中有球,我们必须知道 s[0] 和每个 s[i] 的关系
转化为最小生成树模型”

——吕欣

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <queue>
 6 #include <vector> 
 7 #include <algorithm>
 8 #define max(a, b) ((a) > (b) ? (a) : (b))
 9 #define min(a, b) ((a) < (b) ? (a) : (b))
10 
11 inline void read(int &x)
12 {
13     x = 0;char ch = getchar(), c = ch;
14     while(ch < '0' || ch > '9')c = ch, ch = getchar();
15     while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0', ch = getchar();
16     if(c == '-')x = -x;
17 }
18 
19 const int INF = 0x3f3f3f3f;
20 const int MAXN = 3000 + 10;
21 const int MAXM = 3000000 + 10;
22 int n,fa[MAXN],u[MAXM],v[MAXM],w[MAXM],cnt[MAXM],tot;
23 
24 bool cmp(int a, int b)
25 {
26     return w[a] < w[b];
27 }
28 
29 int find(int x)
30 {
31     return x == fa[x] ? x : fa[x] = find(fa[x]);
32 }
33 
34 long long ans;
35 
36 int main()
37 {
38     read(n);
39     register int tmp;
40     for(register int i = 1;i <= n;++ i)
41     {
42         for(register int j = i;j <= n;++j)
43         {
44             read(tmp);
45             ++ tot;
46             u[tot] = i, v[tot] = j + 1, w[tot] = tmp;
47             cnt[tot] = tot;
48         }
49         fa[i] = i;
50     }
51     std::sort(cnt + 1, cnt + 1 + tot, cmp);
52     for(register int i = 1;i <= tot;++ i)
53     {
54         int p = cnt[i];
55         int f1 = find(u[p]), f2 = find(v[p]);
56         if(f1 == f2)continue;
57         ans += w[p];
58         fa[f1] = f2;
59     }
60     printf("%lld", ans);
61     return 0;
62 }
BZOJ3714