Room and Moor
Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 79 Accepted Submission(s): 12
Problem Description
PM Room defines a sequence A = {A
1, A
2,..., A
N}, each of which is either 0 or 1. In order to beat him, programmer Moor has to construct another sequence B = {B
1, B
2,... , B
N} of the same length, which satisfies that:
Input
The 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 A i.
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 A i.
Output
Output 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
Source
Recommend
贪心即可 用栈维护区间递增,如果比栈顶小,就合并区间,直到合法为止;
然后每个区间f(a,b)=x*y/(x+y), x代表区间内1的个数,y代表区间内0的个数。
代码:
#include <cstdio>
#include <stack>
using namespace std;
struct Node {
int ae, be;
double ce;
void init()
{
ce=double(be)/double(ae+be);
}
};
int main ()
{
//freopen("data.in","r",stdin);
int n,T,date,oldDate;
int BB;
int BH;
int a,b;
double ans;
Node temp;
stack<Node> q;
scanf("%d",&T);
while (T--)
{
scanf("%d",&n);
a=0,b=0,BB=0,BH=0;
oldDate=1;
for (int i=0;i<n;i++)
{
scanf("%d",&date);
if((date!=oldDate)&&i!=0)
{
temp.ae=a;
temp.be=b;
temp.init();
while (!q.empty()&&temp.ce<q.top().ce)
{
temp.ae=temp.ae+q.top().ae;
temp.be=temp.be+q.top().be;
temp.init();
q.pop();
}
q.push(temp);
if(date==0)
{
a=1;
b=0;
}
else {a=0;
b=1;}
}
else {
if(date==0)
{
a++;
}
else {
b++;
}
}
if((i==n-1)&&date==0)
{
temp.ae=a;
temp.be=b;
temp.init();
while (!q.empty()&&temp.ce<q.top().ce)
{
temp.ae=temp.ae+q.top().ae;
temp.be=temp.be+q.top().be;
temp.init();
q.pop();
}
q.push(temp);
}
oldDate=date;
}
ans=0;
while (!q.empty())
{
ans+=q.top().ce*q.top().ae;
q.pop();
}
printf("%.6f\n",ans);
}
return 0;
}