2014西安赛区C题

时间:2024-09-24 15:04:32

将A[i]同他后面比他小的建边,然后求最大密度子图

#include <iostream>
#include <algorithm>
#include <string.h>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const int maxn=;
const double eps=0.00000001;
const double INF=;
vector<int>ans;
struct Dinic
{
struct Edge
{
int from,to;
double cap,flow;
Edge(int cfrom=,int cto=,double ccap=,double cflow=)
{
from=cfrom; to=cto; cap=ccap; flow=cflow;
}
};
int n,m,s,t;
vector<Edge>edges;
vector<int>G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init(int n)
{
this->n=n;
m=;
edges.clear();
for(int i=; i<=n; i++)G[i].clear();
}
void AddEdge(int from,int to,double cap)
{
edges.push_back(Edge(from,to,cap,));
edges.push_back(Edge(to,from,,));
m+=;
G[from].push_back(m-);
G[to].push_back(m-);
}
bool BFS()
{
memset(vis,false,sizeof(vis));
queue<int>Q;
Q.push(s);
d[s]=;
vis[s]=;
while(!Q.empty())
{
int x=Q.front(); Q.pop();
for(int i=; i<G[x].size(); i++)
{
Edge &e =edges[G[x][i]];
if(vis[e.to]==false&&e.cap>e.flow)
{
vis[e.to]=;
d[e.to]=d[x]+;
Q.push(e.to);
}
}
}
return vis[t];
}
double DFS(int x, double a)
{
if(x==t||a==)return a;
double flow=,f;
for(int &i=cur[x]; i<G[x].size(); i++)
{
Edge &e=edges[G[x][i]];
if(d[x]+==d[e.to]&&(f=DFS(e.to,min(a,e.cap-e.flow)))>)
{
e.flow+=f;
edges[G[x][i]^].flow-=f;
flow+=f;
a-=f;
if(a==)break;
}
}
return flow;
}
double Maxflow(int s,int t)
{
this->s=s; this->t=t;
double flow=;
while(BFS())
{
memset(cur,,sizeof(cur));
flow+=DFS(s,INF);
}
return flow;
}
}T;
int d[maxn];
int A[maxn*maxn],B[maxn*maxn];
int N[maxn];
double U;
void build(int n,int m,double g)
{
T.init(n+);
for(int i=; i<=n; i++)
{
T.AddEdge(n+,i,U);
T.AddEdge(i,n+,U+g*-d[i]);
}
for(int i=; i<m; i++)
{
T.AddEdge(A[i],B[i],);
T.AddEdge(B[i],A[i],);
}
}
int main()
{
int cas;
scanf("%d",&cas);
for(int cc=; cc<=cas; cc++)
{
int n;
scanf("%d",&n);
for(int i=; i<=n; i++)
scanf("%d",&N[i]);
int m=;
memset(d,,sizeof(d));
for(int i=; i<=n; i++)
for(int j=i+; j<=n; j++)
if(N[i]>N[j]){
d[N[i]]++;d[N[j]]++;
A[m]=N[i];B[m]=N[j]; m++;
}
if(m==)
{
printf("Case #%d: 0.0000000\n",cc);
continue;
}
double L=,R=m;
U=m;
while(R-L>=eps)
{
double mid=(L+R)*0.5;
build(n,m,mid);
double ans=T.Maxflow(n+,n+);
ans=(U*n-ans)*0.5;
if(ans>)L=mid;
else R=mid;
}
printf("Case #%d: %.7lf\n",cc,L );
}
return ;
}
/*
2
5
3 4 2 5 1
5
2 1 3 4 5
*/