标签:最小 pop scanf mem queue algorithm == 思路 矩阵
给出一个 \(N \times N\) 的矩阵 \(B\) 和一个 \(1\times N\) 的矩阵 \(C\)。
求出一个 \(1 \times N\) 的 \(01\) 矩阵 \(A\),使得 \(D = (A \times B?C)×A^T\)最大。
输出 \(D\)。
先对式子进行化简:
不妨设\(B = (a_{ij})_{n \times n}\),\(C = (c_i)_n\)
发现这道题就是最大获利那道题的变形,考虑最大密度子图
两点之间的边权为\(a_{ij} + a_{ji}\),点权为\(-c_i + a_{ii}\)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 510, M = (250000 + N * 2) * 2, inf = 1e8;
int n, S, T;
int h[N], e[M], ne[M], f[M], idx;
int cur[N], d[N];
int dg[N], p[N];
int w[N][N];
void add(int a, int b, int c1, int c2)
{
e[idx] = b, f[idx] = c1, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, f[idx] = c2, ne[idx] = h[b], h[b] = idx ++;
}
bool bfs()
{
memset(d, -1, sizeof(d));
queue<int> que;
que.push(S);
d[S] = 0, cur[S] = h[S];
while(que.size()) {
int t = que.front();
que.pop();
for(int i = h[t]; ~i; i = ne[i]) {
int ver = e[i];
if(d[ver] == -1 && f[i]) {
d[ver] = d[t] + 1;
cur[ver] = h[ver];
if(ver == T) return true;
que.push(ver);
}
}
}
return false;
}
int find(int u, int limit)
{
if(u == T) return limit;
int flow = 0;
for(int i = cur[u]; ~i && flow < limit; i = ne[i]) {
cur[u] = i;
int ver = e[i];
if(d[ver] == d[u] + 1 && f[i]) {
int t = find(ver, min(f[i], limit - flow));
if(!t) d[ver] = -1;
f[i] -= t, f[i ^ 1] += t, flow += t;
}
}
return flow;
}
int dinic()
{
int res = 0, flow;
while(bfs()) {
while(flow = find(S, inf)) {
res += flow;
}
}
return res;
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof(h));
S = 0, T = n + 1;
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
int x;
scanf("%d", &x);
w[i][j] = x;
}
}
for(int i = 1; i <= n; i ++) {
for(int j = i + 1; j <= n; j ++) {
add(i, j, w[i][j] + w[j][i], w[i][j] + w[j][i]);
dg[i] += w[i][j] + w[j][i];
dg[j] += w[i][j] + w[j][i];
}
}
for(int i = 1; i <= n; i ++) {
scanf("%d", &p[i]);
p[i] = -p[i] + w[i][i];
}
int U = 0;
for(int i = 1; i <= n; i ++) U = max(U, 2 * p[i] + dg[i]);
for(int i = 1; i <= n; i ++) add(S, i, U, 0);
for(int i = 1; i <= n; i ++) add(i, T, U - 2 * p[i] - dg[i], 0);
printf("%d\n", (n * U - dinic()) / 2);
return 0;
}
标签:最小 pop scanf mem queue algorithm == 思路 矩阵
原文地址:https://www.cnblogs.com/miraclepbc/p/14408216.html