题目链接:poj 2175
消圈算法,可以用来判断当前的方案是否是令费用最小的方案。若存在一个负环,那么一定可以找到比当前方案更优的方案。对于这道题,我们只需用残量网络建图,跑spfa判断这个图是否有环。若有环,沿着环更改方案即可。具体怎么建图,挖坑待填。
先贴上代码。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int N,M,T;
int a[110][110],count[110],vis[220],dis[220],s[220],head[220],fa[220];
struct node{int x,y,v;}p[110],pos[110];
struct edge{int v,next,w;}e[100000];
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int k=0;
void adde(int u,int v,int w){
e[k].v=v; e[k].w=w; e[k].next=head[u]; head[u]=k++;
}
int find(int i,int j){
return fabs(p[i].x-pos[j].x)+fabs(p[i].y-pos[j].y);
}
queue<int>q;
int spfa(){
memset(dis,0x3f3f3f,sizeof(dis));
q.push(T); vis[T]=1; dis[T]=0; s[T]++;
while(!q.empty()){
int u=q.front(); q.pop();
for(int i=head[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(dis[v]>dis[u]+e[i].w){
dis[v]=dis[u]+e[i].w; fa[v]=u;
if(!vis[v]){
q.push(v); vis[v]=1; s[v]++;
if(s[v]>N+M+2)return v;//if here has a negative loop.
}
}
}
vis[u]=0;
}
return -1;
}
int main(){
memset(head,-1,sizeof(head));
N=read(); M=read(); T=N+M+1;
for(int i=1;i<=N;i++){
p[i].x=read(); p[i].y=read(); p[i].v=read();
}
for(int i=1;i<=M;i++){
pos[i].x=read(); pos[i].y=read(); pos[i].v=read();
}
for(int i=1;i<=N;i++)
for(int j=1;j<=M;j++){
a[i][j]=read(); count[j]+=a[i][j];
int temp=find(i,j); adde(i,N+j,temp);
if(a[i][j])adde(N+j,i,-temp);
}
for(int i=1;i<=M;i++){
if(count[i])adde(T,N+i,0);
if(count[i]<pos[i].v)adde(N+i,T,0);
}
int t=spfa();//check if there is a negative loop.
if(t==-1)printf("OPTIMAL\n");
else{
memset(vis,0,sizeof(vis));
int S=t,col;
while(1){
if(!vis[S]){vis[S]=1; S=fa[S];}
else {col=S; break;}
}
do{
int u=fa[S],v=S;
if(u>N && u<=N+M && v<=N)a[v][u-N]--;
if(u<=N && v>N && v<=N+M)a[u][v-N]++;
S=fa[S];
}while(S!=col);
printf("SUBOPTIMAL\n");
for(int i=1;i<=N;i++){
for(int j=1;j<=M;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
}
return 0;
}