[codevs 1227] 方格取数2
[codevs 1227] 方格取数 2
题解:
注:这是CODEVS的方格取数2,走k次的版本。
因为每个格子可以走无数次,但走过一次之后数字就变成了0,也就是只有一次可以加上格子里的数字。所以要拆点(X->Xi,Xj),在Xi和Xj之间连一条容量为1,费用为数字的相反数的边(取走该格数字),再连一条容量为INF,费用为0的边(第2,3...n次走该格)。再从每个格子的Xj点向左面及下面的格子的Xi点连一条容量为1,费用为0的边,最后从源点向第一个格子的Xi连一条容量为k(走k次)费用为0,从最后一个点的Xj向汇点连一条同样的边。求解最小费用最大流,费用的相反数就是答案。
代码:
总时间耗费: 149ms
总内存耗费: 1 kB
总内存耗费: 1 kB
#include<cstdio> #include<iostream> #include<vector> #include<queue> #include<algorithm> using namespace std; const int INF = 1e8 + 7; const int maxn = 50 * 50 * 2 + 10; struct Edge{ int from, to, cap, flow, cost; }; vector<Edge> edges; vector<int> G[maxn]; int n, k, s, t; void encode(int i, int j, int& THIS, int& NEXT, int& DOWN, int& LEFT) { i--; j--; THIS = i * n + j + 1; NEXT = THIS + n*n; DOWN = i < n-1 ? THIS + n : 0; LEFT = j < n-1 ? THIS + 1 : 0; } void AddEdge(int from, int to, int cap, int cost) { edges.push_back((Edge){from, to, cap, 0, cost}); edges.push_back((Edge){to, from, 0, 0, -cost}); int m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } int d[maxn], a[maxn], p[maxn]; bool inq[maxn]; bool SPFA(int &cost) { for(int i = 0; i <= t; i++) d[i] = INF; memset(inq, 0, sizeof(inq)); d[s] = 0; inq[s] = 1; a[s] = INF; p[s] = 0; 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[u] + e.cost < d[e.to]) { 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]) { Q.push(e.to); inq[e.to] = 1; } } } } if(d[t] == INF) return 0; cost += d[t] * a[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 1; } int maxflow() { int cost = 0; while(SPFA(cost)); return cost; } int main() { cin >> n >> k; s = 0; t = n*n*2 + 1; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) { int THIS, NEXT, DOWN, LEFT; encode(i, j, THIS, NEXT, DOWN, LEFT); int w; cin >> w; AddEdge(THIS, NEXT, 1, -w); AddEdge(THIS, NEXT, INF, 0); if(LEFT) AddEdge(NEXT, LEFT, INF, 0); if(DOWN) AddEdge(NEXT, DOWN, INF, 0); } AddEdge(s, 1, k, 0); AddEdge(t-1, t, k, 0); cout << -maxflow() << endl; return 0; }