题意:给出一些数字,找出逆序对。令 逆序对的个数/数字个数 最大。
解法:我们先将逆序对用线标出来,然后就会发现这就是 边的数量 / 点的数量。这就是图的密度的定义。找最大密度则是用最大密集子图。求最大密集子图的方法见《最小割模型在信息学竞赛中的应用》。
代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
const int maxn = 110;
const int maxm = 1e6 + 5;
const double eps = 1e-7;
const int INF = 0x3f3f3f3f;
using namespace std;
int n, m;
int head[maxn],cur[maxn],nx[maxm<<1],to[maxm<<1],ppp=0,thead[maxn];
double flow[maxm<<1];
struct Dinic {
int dis[maxn];
int s, t;
double ans;
void init() {
memset(head, -1, sizeof(head));
ppp = 0;
}
void AddEdge(int u, int v, double c) {
to[ppp]=v;flow[ppp]=c;nx[ppp]=head[u];head[u]=ppp++;swap(u,v);
to[ppp]=v;flow[ppp]=0;nx[ppp]=head[u];head[u]=ppp++;
}
bool BFS() {
memset(dis, -1, sizeof(dis));
dis[t] = 1;
queue<int> Q;
Q.push(t);
while(!Q.empty()) {
int x = Q.front();
Q.pop();
for(int i = head[x]; ~i; i = nx[i]) {
if(flow[i^1] > 0 && dis[to[i]] == -1) {
dis[to[i]] = dis[x] + 1;
Q.push(to[i]);
}
}
}
return dis[s] != -1;
}
double DFS(int x, double maxflow) {
if(x == t || !maxflow){
ans += maxflow;
return maxflow;
}
double ret = 0, f;
for(int &i = cur[x]; ~i; i = nx[i]) {
if(dis[to[i]] == dis[x] - 1 && (f = DFS(to[i], min(maxflow, flow[i])))) {
ret += f;
flow[i] -= f;
flow[i^1] += f;
maxflow -= f;
if(!maxflow)
break;
}
}
return ret;
}
double solve(int source, int tank) {
s = source;
t = tank;
ans = 0;
while(BFS()) {
memcpy(cur, head, sizeof(cur));
DFS(s, INF);
}
return ans;
}
}dinic;
int deg[maxn], u[maxm], v[maxm], a[maxn];
void build(double g) {
dinic.init();
int s = 0, t = n + 1;
for(int i = 1; i <= n; i++) {
dinic.AddEdge(s, i, m);
dinic.AddEdge(i, t, m + 2 * g - deg[i]);
}
for(int i = 1; i <= m; i++) {
dinic.AddEdge(u[i], v[i], 1.0);
dinic.AddEdge(v[i], u[i], 1.0);
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
int T, Case = 1;
scanf("%d", &T);
while(T--) {
memset(deg, 0, sizeof(deg));
scanf("%d", &n);
m = 0;
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for(int i = 1; i <= n; i++) {
for(int j = i + 1; j <= n; j++) {
if(a[i] > a[j]) {
m++;
u[m] = i, v[m] = j;
deg[i]++, deg[j]++;
}
}
}
// if(m == 0) {
// printf("Case #%d: %.12f\n", Case++, 1.0);
// continue;
// }
double front = 0, back = m;
double e = 1.0 / n / n; //引理4.1 无向图G中
while(back - front > eps) { //任意两个具有不同密度的子图G1,G2
double g = (front + back) / 2.0;//它们的密度差不小于1/n/n
build(g);
double tmp = dinic.solve(0, n + 1);
if(n * m - tmp > eps) //即使两边乘以-1,依然要趋于0
front = g; //大于0说明g还不够大,使得tmp太小
else
back = g;
}
printf("Case #%d: %.12f\n", Case++, front);
}
return 0;
}