2020 杭电多校4 1007 Go Running (最大流)

题意:

有一些学生在 x x 轴上跑步,速度为 1 1 ,可以有两种方向,并且具有起始时间、结束时间和起始位置。现在有 n n 个监视器,每个监视器记录了 t x (t,x) ,表示在t时刻, x x 位置有人。问最少有多少个学生有去跑步。

思路:

如果建立 y y 轴为时间,那么每个学生就是 y = x + b y=x+b、 y = x + b y=-x+b 直线上的一段,而监视器就是坐标系上的点,现在就是问怎么选择最少的线段,使得点全被覆盖。而对于一个点,就会对应两条线可以覆盖它,而一个点可以用截距 b b 来代表,就相当于一个二分图匹配问题,然后求最大匹配,进而转化为最大流来解决。

代码:

#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define PII pair<int,int>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define pb push_back
#define cwk freopen("D:\\c++\\in.txt","r",stdin),freopen("D:\\c++\\out.txt","w",stdout)
using namespace std;
const int N=5e5+10;
const int M=1e6+10;
int T;
int n;
int a[N],b[N];
vector<int>v;
int getid(int x) {
	return lower_bound(v.begin(),v.end(),x)-v.begin()+1;
}
struct Maxflow{
	int h[N],cur[N],ne[M],to[M],tot,deep[N],s,t,mx;
	ll flow[M],ans;
	inline void init(int a,int b,int c){
		s=a;t=b;mx=c;
		for(int i=0;i<M;i++)ne[i]=0;
		for(int i=0;i<N;i++)h[i]=0;
		tot=1;ans=0;
	}
	inline void addedge(int x,int y,int z){
		to[++tot]=y;ne[tot]=h[x],h[x]=tot,flow[tot]=z;
		swap(x,y);
		to[++tot]=y;ne[tot]=h[x],h[x]=tot,flow[tot]=0;
	}
	inline bool bfs(){
		for(int i=0;i<=mx;i++)deep[i]=-1;
		queue<int>q;
		q.push(s);deep[s]=0;
		for(int i=0;i<=mx;i++)cur[i]=h[i];
		while(!q.empty())
		{
			int now=q.front();q.pop();
			for(int i=h[now];i;i=ne[i]){
				int v=to[i];
				if(deep[v]==-1&&flow[i]>0)deep[v]=deep[now]+1,q.push(v);
			}
		}
		return deep[t]!=-1;
	}
	inline ll dfs(int u,ll op){
		if(u==t||op==0)return op;
		ll f=0,us=0;
		for(int i=cur[u];i;i=ne[i]){
			cur[u]=i;
			int v=to[i];
			if(deep[v]==deep[u]+1&&flow[i]>0){
				us=dfs(v,min(op,flow[i]));
				if(!us)continue;
				f+=us;op-=us;
				flow[i]-=us;flow[i^1]+=us;
				if(!op)break;
			}
		}
		if(!f)deep[u]=-1;
		return f;
	}
	inline ll maxflow(){
		while(bfs()){
			ans+=dfs(s,inf);
		}
		return ans;
	}
}F;
int main()
{
	//cwk;
	scanf("%d",&T);
	while(T--) {
		scanf("%d",&n);
		v.clear();
		for(int i=1;i<=n;i++) 
			scanf("%d%d",&a[i],&b[i]),v.pb(a[i]+b[i]),v.pb(a[i]-b[i]);
		sort(v.begin(),v.end());
		v.erase(unique(v.begin(),v.end()),v.end());//离散化
		int m=v.size();
		F.init(0,2*m+1,2*m+1);
		for(int i=1;i<=m;i++) {
			F.addedge(0,i,1);
			F.addedge(i+m,2*m+1,1);
		}
		for(int i=1;i<=n;i++) {
			int l=getid(a[i]-b[i]);
			int r=getid(a[i]+b[i]);
			F.addedge(l,r+m,inf);
		}
		ll ans=F.maxflow();
		printf("%lld\n",ans);
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40400202/article/details/107699009