bzoj 3275 Number
内容
Description
有N个正整数,需要从中选出一些数,使这些数的和最大。
若两个数a,b同时满足以下条件,则a,b不能同时被选
1:存在正整数C,使a*a+b*b=c*c
2:gcd(a,b)=1
Input
第一行一个正整数n,表示数的个数。n<=3000
第二行n个正整数a1,a2,…an
Output
最大的和
Sample Input
5
3 4 5 6 7
Sample Output
22
题解
首先想对这些数黑白染色,然后按照那种模型建图。
发现奇数不会构成勾股数,偶数不会满足第二条条件。
然后就按照奇偶染色就好了。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#define N 400030
using namespace std;
const int inf = 0x3f3f3f3f;
struct flows {
struct node {
int to, next, flow;
} e[N];
int tot, st[N], dis[N], cur[N];
void init() {
tot = -1, memset(e, -1, sizeof e),
memset(st, -1, sizeof st);
}
void add(int x, int y, int z) {
e[++tot].to = y;
e[tot].flow = z;
e[tot].next = st[x];
st[x] = tot;
}
void add_edge(int x, int y, int z) {
// printf("add%d %d %d\n", x, y, z);
add(x, y, z), add(y, x, 0);
}
queue <int> que;
int bfs(int S, int T) {
memcpy(cur, st, sizeof st);
memset(dis, 0, sizeof dis);
while (!que.empty()) que.pop();
que.push(S);
dis[S] = 1;
while(!que.empty()) {
int now = que.front();
que.pop();
for (int i = st[now]; ~i; i = e[i].next)
if (e[i].flow && !dis[e[i].to]) {
dis[e[i].to] = dis[now] + 1;
if (e[i].to == T) return 1;
que.push(e[i].to);
}
}
return 0;
}
int finds(int now, int T, int flow) {
if (now == T)
return flow;
int f;
for (int i = cur[now]; ~i; i = e[i].next) {
cur[now] = i;
if (e[i].flow && dis[e[i].to] == dis[now] + 1 &&
(f = finds(e[i].to, T, min(flow, e[i].flow)))) {
e[i].flow -= f;
e[i^1].flow += f;
return f;
}
}
return 0;
}
int dinic(int S, int T) {
int flow = 0, x;
while(bfs(S, T)) {
while(x = finds(S, T, inf)) {
flow += x;
}
}
return flow;
}
}flow;
int n, m, a[N], ans;
int gcd(int a, int b) { return !b ? a : gcd(b, a % b); }
main() {
scanf("%d", &n);
flow.init();
int S = 0, T = n + 1;
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]), ans += a[i];
if (a[i] & 1)
flow.add_edge(S, i, a[i]);
else
flow.add_edge(i, T, a[i]);
}
for (int i = 1; i <= n; ++i)
for (int j = i + 1; j <= n; ++j) {
int t = a[i] * a[i] + a[j] * a[j], s = (int)sqrt(t);
if (s * s == t && gcd(a[i], a[j]) == 1)
if (a[i] & 1)
flow.add_edge(i, j, inf);
else
flow.add_edge(j, i, inf);
}
printf("%d\n", ans - flow.dinic(S, T));
}