题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=4923
题目大意:给你一串A = {A1, A2,..., AN}由{0,1}组成, 你要构造出一字符串 B = {B1, B2,... , BN}与A的长度相同。
求出这个最小值。
最开始见到这个题目先是想了想应该怎么做,比如先把A串处理一下。
1)把A前面的0去掉
2)把A后面的1去掉
3)将每部分的特值算出来。
举个栗子吧,字符串A将前的0去掉,后面的1去掉之后,字符串可以简化为N个 {1..1 0...0} 组成的单位。
比如组成之后是这样的
10 110 10 1110 每部分取到最小值的时候x取值分别为 假设每组有a个1,b个0,则每组取到最小值时x取值是a/(a+b)
x1 x2 x3 x4
1/2 2/3 1/2 3/4
如果其x的值是一个递增的就好了,思路在这就断了....... 甚至还想到了最大上升子串......还是无果.......
赛后看解题报告,其实想法还是不够,差了最后一步。
我们这样来想
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
const int maxn=1e5+10;
const double eps=1e-8;
const int INF=2e9;
struct node{
int id,num0,num1;
double rate;
}e[maxn],f,g;
int t,a[maxn];
stack<node>mm;
int main()
{
//freopen("D:\\in.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
int i,j,k,n,p,q;
double num,ans=0;
t=0;
scanf("%d",&n);
int l=0,r=n-1;
for(i=0;i<n;i++)scanf("%d",&a[i]);
a[n]=1;
while(a[l]==0)l++;
while(a[r]==1)r--;
if(l>r){printf("0.000000\n");continue;}
for(i=l;i<=r;)
{
j=k=0;
while(a[i]==1){i++;j++;}
while(a[i]==0){i++;k++;}
e[t].id=t;e[t].num1=j;e[t].num0=k;e[t].rate=1.0*j/(j+k);
t++;
}
while(!mm.empty())mm.pop();
for(i=0;i<t;i++)
{
if(mm.empty())mm.push(e[i]);
else
{
f=mm.top();
if(f.rate<=e[i].rate)mm.push(e[i]);
else
{
g=e[i];
while(true)
{
f=mm.top();
if(f.rate>g.rate)
{
g.num1+=f.num1;
g.num0+=f.num0;
g.rate=1.0*g.num1/(g.num0+g.num1);
mm.pop();
}
else
{
mm.push(g);
break;
}
if(mm.empty())
{
mm.push(g);
break;
}
}
}
}
}
while(!mm.empty())
{
f=mm.top();
mm.pop();
ans+=f.rate*f.rate*f.num0+(1-f.rate)*(1-f.rate)*f.num1;
}
printf("%.6f\n",ans);
}
return 0;
}
/*
10
5
1 0 0 1 0
10
1 0 1 0 0 0 0 1 0 0
1.166667
2.095238
24996.075303
24992.671476
24996.140534
24998.633044
24998.119559
24996.859735
*/