# TZOJ4777: 方格取数

## 4777: 方格取数

Time Limit(Common/Java):1000MS/3000MS     Memory Limit:65536KByte
Total Submit: 11            Accepted:10

Description

Input

Output

Sample Input

8
2 3 13
2 6 6
3 5 7
4 4 14
5 2 21
5 6 4
6 3 15
7 2 14
0 0 0

Sample Output

67

#include <bits/stdc++.h>
using namespace std;
#define max4(a, b, c, d) max(max(a, b), max(c, d))
int dp[21][11][11];
int a[11][11];
int main()
{
int n, x, y, z;
scanf("%d", &n);
while (~scanf("%d%d%d", &x, &y, &z) && (x || y || z))a[x][y] = z;
for (int k = 1; k < n * 2; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
if (i > k || j > k || k - j + 1 > n || k - i + 1 > n)continue;
dp[k][i][j] = max4(dp[k - 1][i][j], dp[k - 1][i - 1][j], dp[k - 1][i][j - 1], dp[k - 1][i - 1][j - 1]);
dp[k][i][j] += a[k - j + 1][j];
if (i != j)dp[k][i][j] += a[k - i + 1][i];
}
cout << dp[n * 2 - 1][n][n];
return 0;
}

#include <bits/stdc++.h>
using namespace std;

const int N = 1e4 + 5;
const int M = 1e5 + 5;
const int INF = 0x3f3f3f3f;

int FIR[N], TO[M], CAP[M], FLOW[M], COST[M], NEXT[M], tote;
int pre[N], dist[N], q[400000];
bool vis[N];
int n, k, S, T;
void init()
{
tote = 0;
memset(FIR, -1, sizeof(FIR));
}
void add(int u, int v, int cap, int cost)
{
TO[tote] = v;
CAP[tote] = cap;
FLOW[tote] = 0;
COST[tote] = cost;
NEXT[tote] = FIR[u];
FIR[u] = tote++;

TO[tote] = u;
CAP[tote] = 0;
FLOW[tote] = 0;
COST[tote] = -cost;
NEXT[tote] = FIR[v];
FIR[v] = tote++;
}
bool SPFA(int s, int t)
{
memset(dist, INF, sizeof(dist));
memset(vis, false, sizeof(vis));
memset(pre, -1, sizeof(pre));
dist[s] = 0;
vis[s] = true;
q[1] = s;
int head = 0, tail = 1;
{
vis[u] = false;
for (int v = FIR[u]; v != -1; v = NEXT[v])
{
if (dist[TO[v]] > dist[u] + COST[v] && CAP[v] > FLOW[v])
{
dist[TO[v]] = dist[u] + COST[v];
pre[TO[v]] = v;
if (!vis[TO[v]])
{
vis[TO[v]] = true;
q[++tail] = TO[v];
}
}
}
}
return pre[t] != -1;
}
void MCMF(int s, int t, int &cost, int &flow)
{
flow = cost = 0;
while (SPFA(s, t))
{
int Min = INF;
for (int v = pre[t]; v != -1; v = pre[TO[v ^ 1]])
Min = min(Min, CAP[v] - FLOW[v]);
for (int v = pre[t]; v != -1; v = pre[TO[v ^ 1]])
{
FLOW[v] += Min;
FLOW[v ^ 1] -= Min;
cost += COST[v] * Min;
}
flow += Min;
}
}
int main()
{
int ca;
cin>>ca;
while(ca--)
{
init();
cin >> n >> k;
S = 0;
T = n * n * 2 + 1;
int ff=n*n;
for (int i = 1; i <= n; i++)
for (int j = 1, x; j <= n; j++)
{
cin>>x;
int a=(i-1)*n+j,b=a+1,c=a+n;
}
add(T - 1, T, k, 0);
int cost, flow;
MCMF(S, T, cost, flow);
printf("%d\n", -cost);
}
return 0;
}

posted @ 2019-07-15 21:52  暴力都不会的蒟蒻  阅读(...)  评论(... 编辑 收藏