Room and moor
Problem descriptionpm room defines a sequence a = {A1, A2 ,..., an}, each of which is either 0 or 1. in order to beat him, programmer Moor has to construct another sequence B = {b1, b2 ,..., BN} of the same length, which satisfies that:
Inputthe input consists of multiple test cases. The number of test cases T (t <= 100) occurs in the first line of input.
For each test case:
The first line contains a single integer N (1 <= n <= 100000), which denotes the length of A and B.
The second line consists of N integers, where the ith denotes AI.
Outputoutput the minimal f (a, B) when B is optimal and round it to 6 decimals.
Sample Input
4 9 1 1 1 1 1 0 0 1 1 9 1 1 0 0 1 1 1 1 1 4 0 0 1 1 4 0 1 1 1
Sample output
1.428571 1.000000 0.000000 0.000000
Question: I will not talk about it anymore.
SL: it is actually a greedy idea.
There are many explanations on the Internet. I didn't figure it out during the competition... Haha.
1 // By caonima
2 // hehe
3 # include <cstdio>
4 # include <cstring>
5 # include <stack>
6 # include <queue>
7 # include <vector>
8 # include <algorithm>
9 Using namespace STD;
10 const int max = 1e6 + 10;
11 struct node {
12 INT one, zero;
13 double val;
14} V [Max];
15 stack <node> ans;
16 int A [Max];
17 void Init (){
18 while (! Ans. Empty () ans. Pop ();
19}
20 int main (){
21 int cas, N;
22 scanf ("% d", & CAS );
23 while (CAS --){
24 scanf ("% d", & N );
25 For (INT I = 1; I <= N; I ++ ){
26 scanf ("% d", & A [I]);
27}
28 A [n + 1] = 1;
29 int L = 1, R = N;
30 While (A [l] = 0) l ++;
31 While (A [R] = 1) r --;
32 If (L> = r) printf ("0.000000 \ n ");
33 else {
34 int id = 0;
35 For (INT I = L; I <= r ;){
36 int cnt0 = 0, cnt1 = 0;
37 while (A [I] = 1 ){
38 cnt1 ++; I ++;
39}
40 while (A [I] = 0 ){
41 cnt0 ++; I ++;
42}
43 V [ID]. One = cnt1; V [ID]. Zero = cnt0;
44 V [ID ++]. Val = (double) cnt1/(double) (cnt0 + cnt1 );
45}
46 Init ();
47 for (INT I = 0; I <ID; I ++ ){
48
49 If (ANS. Empty () ans. Push (V [I]);
50 else {
51 node VN = ans. Top ();
52 If (VN. Val <= V [I]. Val) ans. Push (V [I]);
53 else {
54 node T = V [I];
55 while (true ){
56 node vx = ans. Top ();
57 if (VX. Val> T. Val ){
58 T. One + = VX. One; T. Zero + = VX. zero;
59 T. Val = (double) T. One/(double) (T. One + T. Zero );
60 ans. Pop ();
61}
62 else {
63 ans. Push (t );
64 break;
65}
66 If (ANS. Empty ()){
67 ans. Push (t );
68 break;
69}
70}
71}
72}
73}
74 double res = 0;
75 while (! Ans. Empty ()){
76 node VN = ans. Top ();
77 ans. Pop ();
78 res + = Vn. Val * VN. Val * VN. Zero + (1-vn.val) * (1-vn.val) * VN. One;
79}
80 printf ("%. 6lf \ n", Res );
81}
82
83}
84}