码迷,mamicode.com
首页 > 其他好文 > 详细

BZOJ 3275 Number && 3158 千钧一发 最小割

时间:2015-01-24 17:26:22      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:bzoj   网络流   最小割   

题目大意:给出一些数字,要求选出一些数字并保证所有数字和最大,要求这其中的数字任意两个至少满足一个条件,则不能同时被选:1.这两个数的平方和是完全平方数。2.gcd(a,b) = 1。


思路:我们可以将奇数和偶数分开来讨论,奇数不满足1,偶数不满足2,所以奇数和奇数,偶数和偶数不会互相影响。之后O(n^2)的讨论其他数字对,有影响就连边,流量正无穷,最后跑最小割最最大获利。


CODE:

#define _CRT_SECURE_NO_WARNINGS

#include <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 3010
#define MAXE 2000000
#define INF 0x3f3f3f3f
#define S 0
#define T (MAX - 1)
#define EPS 1e-7
using namespace std;

struct MaxFlow{
	int head[MAX],total;
	int next[MAXE],aim[MAXE];
	long long flow[MAXE];

	int deep[MAX];

	MaxFlow():total(1) {}
	void Add(int x,int y,long long f) {
		next[++total] = head[x];
		aim[total] = y;
		flow[total] = f;
		head[x] = total;
	}
	void Insert(int x,int y,long long f) {
		Add(x,y,f);
		Add(y,x,0);
	}
	bool BFS() {
		static queue<int> q;
		while(!q.empty())	q.pop();
		memset(deep,0,sizeof(deep));;
		deep[S] = 1;
		q.push(S);
		while(!q.empty()) {
			int x = q.front(); q.pop();
			for(int i = head[x]; i; i = next[i])
				if(flow[i] && !deep[aim[i]]) {
					deep[aim[i]] = deep[x] + 1;
					q.push(aim[i]);
					if(aim[i] == T)	return true;
				}
		}
		return false;
	}
	long long Dinic(int x,long long f) {
		if(x == T)	return f;
		long long temp = f;
		for(int i = head[x]; i; i = next[i])
			if(flow[i] && temp && deep[aim[i]] == deep[x] + 1) {
				long long away = Dinic(aim[i],min(flow[i],temp));
				if(!away)	deep[aim[i]] = 0;
				flow[i] -= away;
				flow[i^1] += away;
				temp -= away;
			}
		return f - temp;
	}
}solver;

int cnt;
pair<int,int> odd[MAX],even[MAX];
int odds,evens;
int energy[MAX];

int gcd(int x,int y)
{
	return (y ? gcd(y,x % y):x);
}

inline bool Judge(int x,int y)
{
	long long aim = (long long)x * x + (long long)y * y;
	if((long long)(sqrt(aim) + EPS) * (long long)(sqrt(aim) + EPS) == (long long)x * x + (long long)y * y)	return true;
	return false;
}

int main()
{
	cin >> cnt;
	long long ans = 0;
	for(int x,i = 1; i <= cnt; ++i) {
		scanf("%d",&x);
		if(x&1) odd[++odds] = make_pair(x,i);
		else	even[++evens] = make_pair(x,i);
	}
	for(int i = 1; i <= cnt; ++i)
		scanf("%d",&energy[i]),ans += energy[i];
	for(int i = 1; i <= odds; ++i)
		solver.Insert(S,i,energy[odd[i].second]);
	for(int i = 1; i <= evens; ++i)
		solver.Insert(odds + i,T,energy[even[i].second]);
	for(int i = 1; i <= odds; ++i)
		for(int j = 1; j <= evens; ++j)
			if(gcd(odd[i].first,even[j].first) == 1 && Judge(odd[i].first,even[j].first))
				solver.Insert(i,odds + j,INF);
	long long max_flow = 0;
	while(solver.BFS())
		max_flow += solver.Dinic(S,INF);
	cout << ans - max_flow << endl;
	return 0;
}


BZOJ 3275 Number && 3158 千钧一发 最小割

标签:bzoj   网络流   最小割   

原文地址:http://blog.csdn.net/jiangyuze831/article/details/43086333

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!