【题目链接】
http://poj.org/problem?id=3436
没台电脑有P个部件和n台机器,每台机器最大能生产p[i]台电脑,每台机器有输入和输出(加工前后),每个部件输入用0,1,2表示,0表示不能有接受的电脑对应的部件没装好,1表示装好,2表示无所谓。每个部件输出用0,1表示,0表示输出电脑对应的部件没装好,1表示装好满足输入才能输出。问最多能说出多少台电脑?并输出一种方案。
拆点,输除连向输入,根据输出与输入是否满足添加边,权值为输出的生产值,输出方案与原图比较,少多少就说明合作多少。
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define inf 0x3f3f3f3
#define LL long long
#define pii pair
const int N = 1e4+5;
struct Edge{
int v,w,nt;
}edge[2*N];
int s,t,n,m,tot;
int head[105],dis[105]; //链表头和bfs距离标记
int inp[105][20],outp[105][20],p[105]; //输入,输出,产量
bool vis[105][105]; //原图是否通
void init()
{
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
tot = s = 0;
t = 2*m+1;
}
void add(int u,int v,int w)
{
edge[tot].v = v;
edge[tot].nt = head[u];
edge[tot].w = w;
head[u] = tot++;
}
void build() //建图
{
for (int i =1; i <= m; i++)
for (int j = 1; j <= m; j++)
{
if (i == j) continue;
bool fa = true;
for (int k = 0; k < n; k++)
if (outp[i][k]!=inp[j][k] && inp[j][k]!=2)
{
fa = false;
break;
}
if (fa) //输出满足输入就加边
{
add(i+m,j,p[i]);
add(j,i+m,0);
vis[i+m][j] = true;
}
}
for (int i = 1; i <= m; i++)
{
add(i,i+m,p[i]);
add(i+m,i,0);
bool sfa,tfa;
sfa = tfa = true;
for (int j = 0; j < n; j++)
{
if (inp[i][j] == 1)
sfa = false;
if (outp[i][j] != 1)
tfa = false;
}
if (sfa) //与源点相连
{
add(0,i,p[i]);
add(i,0,0);
}
if (tfa) //与汇点相连
{
add(i+m,2*m+1,p[i]);
add(2*m+1,i+m,0);
}
}
}
bool bfs ()
{
memset(dis,-1,sizeof(dis));
dis[s] = 0;
queue<int> q;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = head[u];i+1;i = edge[i].nt)
{
int v = edge[i].v;
if (dis[v] == -1 && edge[i].w)
{
dis[v] = dis[u]+1;
q.push(v);
}
}
}
return dis[t] != -1;
}
int dfs(int u,int flow)
{
if (u == t)
return flow;
int de = flow;
for (int i = head[u];i+1;i = edge[i].nt)
{
int v = edge[i].v;
if (edge[i].w && dis[v]==dis[u]+1)
{
int a = dfs(v,min(de,edge[i].w ));
de -= a;
edge[i].w -= a;
edge[i^1].w += a;
if (de == 0)
return flow;
}
}
return flow - de;
}
int dinic(){
int ans = 0;
while(bfs())
ans += dfs(s,inf);
return ans;
}
void prif()
{
int cnt=0;
for(int i=1;i<=m;i++){
for(int j = head[i+m]; j+1; j = edge[j].nt)
if(vis[i+m][edge[j].v] && edge[j].w<p[i])
cnt++;
}
printf(" %d\n",cnt);
for(int i=1;i<=m;i++)
{
for(int j = head[i+m]; j+1 ; j = edge[j].nt)
if(vis[i+m][edge[j].v] && edge[j].w<p[i])
{
printf("%d %d %d\n",i,edge[j].v,p[i]-edge[j].w);
}
}
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
init();
for (int i = 1; i <= m; i++)
{
scanf("%d",&p[i]);
for (int j = 0; j < n; j++)
scanf("%d",&inp[i][j]);
for(int j = 0; j < n; j++)
scanf("%d",&outp[i][j]);
}
build();
printf("%d",dinic());
prif();
}
return 0;
}