中石油训练赛 - Trading Cards(最大权闭合子图)

题目大意:给出 n 个卡片,可以自由买卖,且价格都是相同的,再给出 m 个集合,如果已经得到了其中一个集合中的卡片,那么可以获得该集合的收益,问如何操作可以使得收益最大化

题目分析:最大权闭合子图的模板题。。感觉亏死了,训练的时候三个英语不好的人根本不会主动去读题,只能被动跟着榜慢慢耗,结果这样一道本应该被秒掉的题目只能赛后看别人翻译的题意再补了

相对于传统的模型,多了一项就是卡片也是可以售出的,又因为售出和购买的价格都是相同的,所以不妨假设初始时就将所有的卡片售出,这样问题就转换成模板题了。。建图方式如下

  1. st -> 每个卡片,权值为对应的 val
  2. 每个卡片 -> 对应的集合,权值为 inf
  3. 每个集合 -> ed,权值为对应的 val

最后答案就是:初始时已有卡片的权值 + 所有集合的权值 - 最小割 了

稍微需要注意的是,第三个样例错了,第一个集合应该是 1 2 3 4 的,少打了一个 4

代码:
 

//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_map>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=110;
 
struct Edge
{
	int to,w,next;
}edge[N*N];//边数
 
int head[N],cnt;
 
void addedge(int u,int v,int w)
{
	edge[cnt].to=v;
	edge[cnt].w=w;
	edge[cnt].next=head[u];
	head[u]=cnt++;
	edge[cnt].to=u;
	edge[cnt].w=0;//反向边边权设置为0
	edge[cnt].next=head[v];
	head[v]=cnt++;
}
 
int d[N],now[N];//深度 当前弧优化
 
bool bfs(int s,int t)//寻找增广路
{
	memset(d,0,sizeof(d));
	queue<int>q;
	q.push(s);
	now[s]=head[s];
	d[s]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(int i=head[u];i!=-1;i=edge[i].next)
		{
			int v=edge[i].to;
			int w=edge[i].w;
			if(d[v])
				continue;
			if(!w)
				continue;
			d[v]=d[u]+1;
			now[v]=head[v];
			q.push(v);
			if(v==t)
				return true;
		}
	}
	return false;
}
 
int dinic(int x,int t,int flow)//更新答案
{
	if(x==t)
		return flow;
	int rest=flow,i;
	for(i=now[x];i!=-1&&rest;i=edge[i].next)
	{
		int v=edge[i].to;
		int w=edge[i].w;
		if(w&&d[v]==d[x]+1)
		{
			int k=dinic(v,t,min(rest,w));
			if(!k)
				d[v]=0;
			edge[i].w-=k;
			edge[i^1].w+=k;
			rest-=k;
		}
	}
	now[x]=i;
	return flow-rest;
}
 
void init()
{
    memset(now,0,sizeof(now));
	memset(head,-1,sizeof(head));
	cnt=0;
}
 
int solve(int st,int ed)
{
	int ans=0,flow;
	while(bfs(st,ed))
		while(flow=dinic(st,ed,inf))
			ans+=flow;
	return ans;
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	init();
	int n,st=N-1,ed=st-1;
	scanf("%d",&n);
	int sum=0;
	for(int i=1;i<=n;i++)
	{
		int val,s;
		scanf("%d%d",&val,&s);
		sum+=val*s;
		addedge(st,i,val);
	}
	int m;
	scanf("%d",&m);
	for(int i=1;i<=m;i++)
	{
		int num,val;
		scanf("%d%d",&num,&val);
		sum+=val;
		addedge(i+n,ed,val);
		while(num--)
		{
			int x;
			scanf("%d",&x);
			addedge(x,i+n,inf);
		}
	}
	printf("%d\n",sum-solve(st,ed));
















   return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/109005221
今日推荐