寿司餐厅
一个数列,每个点都有代号,任意区间都有获利 d[i][j],重复区间算一次,如:选定[1,3],则获利d[1][1], d[2][2], d[3][3], d[1][2], d[2][3], d[1][3]。设代号为x,出现次数为c,则代价为 mx2+cx m x 2 + c x ,求获利-代价的最大值
- 最小割
- 所有区间看作点,设计选与不选的代价是多少
- 特殊的,a[i]只会被形如[1,1]的区间获得
- 对于m*x*x,新建所有的a[i]点,处理所有点之间的依赖关系
- 若选了a,必须选b,则连接a,b,边权为inf **
- 细节,若d为负值,则把它看作代价 **
- S为不选,T为选
- 答案为所有正d和-最小割
- 点较多,最好用当前弧优化的dinic
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#define File(x) "test."#x
#define For(i,s,e) for(int i=(s); i<=(e); i++)
#define Rep(i,s,e) for(int i=(s); i>=(e); i--)
using namespace std;
typedef long long LL;
const int N=500+1,inf=0x7fffffff;
struct Node{
int x,nxt,rest;
}T[N*N];
int n,m,t,sn,a[N],d[N][N],g[N*N],ref[N],S,D,Flow;
int h[N*N],len,hsp[N*N],hss[N][N],cur[N*N],ans;
void addEdge(int x, int y, int flw){
T[++len]=(Node){y,h[x],flw}; h[x]=len;
T[++len]=(Node){x,h[y],0}; h[y]=len;
}
void init(){
memset(h,-1,sizeof(h)); len=1;
For(i,0,1000){
if(g[i]) hsp[i]=++t, ref[t]=i;
}
For(i,1,n) For(j,i,n) hss[i][j]=++sn;
S=1, D=1+t+sn+1;
}
int tag(int x, int flag){
if(flag==1) return x+1;
if(flag==2) return 1+sn+x;
}
int dfs(int,int);
bool bfs();
void dinic();
int main()
{
scanf("%d%d",&n,&m);
For(i,1,n) scanf("%d",&a[i]), g[a[i]]++;
For(i,1,n) For(j,i,n){
scanf("%d",&d[i][j]);
if(d[i][j]>0) ans+=d[i][j];
}
init();
For(i,1,t) addEdge(S,tag(i,2),m*ref[i]*ref[i]);
For(i,1,n) For(j,i,n){
if(i==j){
addEdge(S,tag(hss[i][j],1),a[i]);
addEdge(tag(hsp[a[i]],2),tag(hss[i][j],1),inf);
}
if(d[i][j]>0) addEdge(tag(hss[i][j],1),D,d[i][j]);
else addEdge(S,tag(hss[i][j],1),-d[i][j]);
if(i!=j){
addEdge(tag(hss[i][j-1],1), tag(hss[i][j],1), inf);
addEdge(tag(hss[i+1][j],1), tag(hss[i][j],1), inf);
}
}
dinic();
cout<<ans-Flow<<endl;
return 0;
}
int dis[N*N],front,tail,q[N*N];
bool bfs(){
memset(dis, -1, sizeof(dis));
front=tail=0; q[++tail]=S; dis[S]=0;
while(front!=tail){
int x=q[++front];
if(x==D) return true;
for(int p=h[x]; p!=-1; p=T[p].nxt){
int v=T[p].x;
if(dis[v]==-1 && T[p].rest>0){
dis[v]=dis[x]+1; q[++tail]=v;
}
}
}
return false;
}
int dfs(int x, int minn){
if(x==D || !minn) return minn;
int res=0, fl;
for(int &p=cur[x]; p!=-1; p=T[p].nxt){
int v=T[p].x;
if(dis[v]==dis[x]+1 && (fl=dfs(v, min(minn-res, T[p].rest)))>0){
T[p].rest-=fl; T[p^1].rest+=fl;
res+=fl;
if(res==minn) return minn;
}
}
if(!res) dis[x]=-1;
return res;
}
void dinic(){
Flow=0;
while(bfs()){
For(i,0,D) cur[i]=h[i];
Flow+=dfs(S,inf);
}
}