时间限制: 1 s
空间限制: 128000 KB
题目等级 : 大师 Master
题目描述 Description
给出一个n*n的矩阵,每一格有一个非负整数Aij,(Aij <= 1000)现在从(1,1)出发,可以往右或者往下走,最后到达(n,n),每达到一格,把该格子的数取出来,该格子的数就变成0,这样一共走K次,现在要求K次所达到的方格的数的和最大
输入描述 Input Description
第一行两个数n,k(1<=n<=50, 0<=k<=10)
接下来n行,每行n个数,分别表示矩阵的每个格子的数
输出描述 Output Description
一个数,为最大和
样例输入 Sample Input
3 1
1 2 3
0 2 1
1 4 2
样例输出 Sample Output
11
数据范围及提示 Data Size & Hint
1<=n<=50, 0<=k<=10
一道最简单的拆点网络流居然做了3天,这是个什么状态
#include<cstdio>
#include<climits>
#include<vector>
#include<queue>
#include<iostream>
using namespace std;
#define N 105
#define INF INT_MAX/2
struct work{
struct Edge{
int fr,to,flow,cap,cost;
Edge(int f,int t,int fl,int ca,int co):fr(f),to(t),flow(fl),cap(ca),cost(co){}
};
vector<Edge> edge;vector<int> g[N*N];
int p[N*N],v[N][N],a[N*N],d[N*N];
int n,m,ans,k;
int hash(int i,int j){return (i-1)*n+j;}
int in(){
int x=0;char ch=getchar();
while(ch>'9'||ch<'0') ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x;
}
void Add_Edge(int fr,int to,int cap,int cost){
edge.push_back(Edge(fr,to,0,cap,-1*cost));
edge.push_back(Edge(to,fr,0,0,cost));
m=edge.size();
g[fr].push_back(m-2);
g[to].push_back(m-1);
return;
}
void init(){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
v[i][j]=in();
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
Add_Edge(hash(i,j)*2,hash(i,j)*2+1,INF,0);Add_Edge(hash(i,j)*2,hash(i,j)*2+1,1,v[i][j]);
if(i<n) Add_Edge(hash(i,j)*2+1,hash(i+1,j)*2,INF,0);
if(j<n) Add_Edge(hash(i,j)*2+1,hash(i,j+1)*2,INF,0);
}
return;
}
int spfa(){
int s=hash(1,1)*2,t=hash(n,n)*2+1,x;
queue<int> q;int b[N*N];
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
d[hash(i,j)*2]=INF,b[hash(i,j)*2]=false;
d[hash(i,j)*2+1]=INF,b[hash(i,j)*2+1]=false;
}
b[s]=true,d[s]=0,a[s]=1;q.push(s);
while(!q.empty()){
x=q.front();q.pop();b[x]=false;
for(int i=0;i<g[x].size();i++){
Edge& e=edge[g[x][i]];
if(e.cap>e.flow&&d[e.to]>d[x]+e.cost){
d[e.to]=d[x]+e.cost;
p[e.to]=g[x][i];
a[e.to]=min(a[x],e.cap-e.flow);
if(!b[e.to]) {b[e.to]=true;q.push(e.to);}
}
}
}
if(d[t]==INF) return 0;
ans+=d[t]*a[t];
for(x=t;x!=s;x=edge[p[x]].fr){
edge[p[x]].flow+=a[t],edge[p[x]^1].flow-=a[t];
}
return 1;
}
void solve(){
init();
while(k--&&spfa());
printf("%d",-ans);
return;
}
}s;
int main(){
s.solve();
return 0;
}