http://acm.hdu.edu.cn/showproblem.php?pid=6767
题意:n(50以内)个工人,m(1e8以内)个器材,i工人用j器材的花费为
a
i
∗
j
∗
j
+
b
i
∗
j
+
c
i
a_i*j*j+b_i*j+c_i
ai∗j∗j+bi∗j+ci,求1~n个匹配的最小花费。
思路:
直接做是不行的,m很大,但是大部分是无意义的,根据二次函数对称轴,最多只需要附近n个
j
j
j即可。因此一共
n
2
n^2
n2个点,
n
2
n^2
n2条边,费用流就可以了。
#include<bits/stdc++.h>
using namespace std;
const int maxn=6000;
typedef long long ll;
const ll INF=0x3f3f3f3f;
struct Edge{
int from,to,cap,flow;
ll cost;
};
struct MCMF{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
int inq[maxn];
ll d[maxn];
int p[maxn];
int a[maxn];
int tot;
void init()
{
int mm;
ll a,b,c;
cin>>n>>mm;
tot=n;
s=0,t=5999;
edges.clear();
for(int i=s;i<=t;i++)G[i].clear();
map<ll,int> node;
for(int i=1;i<=n;i++)
{
scanf("%lld%lld%lld",&a,&b,&c);
int mid=b/(-2*a);
AddEdge(s,i,1,0);
int l,r;
if(mid<=0)l=1,r=min(n,mm);
else if(mid>=mm)r=mm,l=max(1,mm-n+1);
else l=max(1,mid-n-2),r=min(mm,mid+n+2);
for(ll j=l;j<=r;j++)
{
if(node.count(j))
{
AddEdge(i,node[j],1,a*j*j+b*j+c);
}
else
{
AddEdge(i,++tot,1,a*j*j+b*j+c);
node[j]=tot;
}
}
}
for(int i=n+1;i<=tot;i++)AddEdge(i,t,1,0);
}
void AddEdge(int from,int to,int cap,ll cost)
{
edges.push_back((Edge){from,to,cap,0,cost});
edges.push_back((Edge){to,from,0,0,-cost});
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool BellmanFord(ll& flow,ll& cost)
{
for(int i=s;i<=tot;i++)d[i]=(1LL<<60);/***切记这里要改***/
d[t]=d[s];
memset(inq,0,sizeof(inq));
d[s]=0;inq[s]=1;p[s]=0;a[s]=INF;
queue<int> Q;
Q.push(s);
while(!Q.empty())
{
int u=Q.front();Q.pop();
inq[u]=0;
for(int i=0;i<G[u].size();i++)
{
Edge& e=edges[G[u][i]];
if(e.cap>e.flow && d[e.to]>d[u]+e.cost)
{
d[e.to]=d[u]+e.cost;
p[e.to]=G[u][i];
a[e.to]=min(a[u],e.cap-e.flow);
if(inq[e.to]==0){inq[e.to]=1;Q.push(e.to);}
}
}
}
if(d[t]==(1LL<<60))return false;
flow+=a[t];
cost+=a[t]*d[t];
int u=t;
while(u!=s)
{
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
u=edges[p[u]].from;
}
return true;
}
ll Mincost()
{
ll flow=0,cost=0;
while(BellmanFord(flow,cost))
{
if(flow!=n)printf("%lld ",cost);
else printf("%lld",cost);
}
putchar('\n');
return cost;
}
}ans;
int main()
{
//freopen("input.in","r",stdin);
int T;
cin>>T;
while(T--)
{
ans.init();
ans.Mincost();
}
return 0;
}