每个点拆点,分别向源/汇连a[i]的边,满足条件的相互连INF的边,答案为sum-maxflow*2。
因为若有几个点不能同时被选,我们要贪心地选择其中和尽量大的部分,这可以由最小割来保证。
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<queue> using namespace std; #define INF 2147483647 #define MAXN 6005 #define MAXM 600301 int v[MAXM],cap[MAXM],en,first[MAXN],next[MAXM]; int d[MAXN],cur[MAXN],A[3005],sumv; queue<int>q; int n,S,T; void Init_Dinic(){memset(first,-1,sizeof(first)); en=0; S=0; T=(n<<1|1);} void AddEdge(const int &U,const int &V,const int &W) {v[en]=V; cap[en]=W; next[en]=first[U]; first[U]=en++; v[en]=U; next[en]=first[V]; first[V]=en++;} bool bfs() { memset(d,-1,sizeof(d)); q.push(S); d[S]=0; while(!q.empty()) { int U=q.front(); q.pop(); for(int i=first[U];i!=-1;i=next[i]) if(d[v[i]]==-1 && cap[i]) { d[v[i]]=d[U]+1; q.push(v[i]); } } return d[T]!=-1; } int dfs(int U,int a) { if(U==T || !a) return a; int Flow=0,f; for(int &i=cur[U];i!=-1;i=next[i]) if(d[U]+1==d[v[i]] && (f=dfs(v[i],min(a,cap[i])))) { cap[i]-=f; cap[i^1]+=f; Flow+=f; a-=f; if(!a) break; } if(!Flow) d[U]=-1; return Flow; } int max_flow() { int Flow=0,tmp=0; while(bfs()) { memcpy(cur,first,((n<<1)+5)*sizeof(int)); while(tmp=dfs(S,INF)) Flow+=tmp; } return Flow; } int gcd(int a,int b){return b==0?a:gcd(b,a%b);} int sqr(const int &x){return x*x;} bool check(const int &a,const int &b) { int t=a*a+b*b; return (sqr((int)sqrt(t))==t&&(gcd(a,b)==1)); } int main() { scanf("%d",&n); for(int i=1;i<=n;++i) { scanf("%d",&A[i]); sumv+=A[i]; } Init_Dinic(); for(int i=1;i<=n;++i) for(int j=1;j<i;++j) if(check(A[i],A[j])) AddEdge(i,j+n,INF), AddEdge(j,i+n,INF); for(int i=1;i<=n;++i) AddEdge(S,i,A[i]), AddEdge(i+n,T,A[i]); printf("%d\n",sumv-(max_flow()>>1)); return 0; }