萌新求助:网络流模板题TLE,90分
  • 板块P2691 逃离
  • 楼主ez_lcw
  • 当前回复10
  • 已保存回复10
  • 发布时间2020/5/9 11:44
  • 上次更新2023/11/7 02:49:24
查看原帖
萌新求助:网络流模板题TLE,90分
118318
ez_lcw楼主2020/5/9 11:44

rt,从“尝试过的题”随笔翻了一道题,发现第8个点T了,1.2s,不知道是死循环了还是常数问题。

// luogu-judger-enable-o2
#pragma GCC optimize("Ofast")

#include<cstdio>
#include<cstring>
#include<iostream>

#define N 40
#define M 20001
#define INF 0x7fffffff

using namespace std;

class Queue{
    public:
        inline void push(int x)
		{
            a[tail++]=x;
        }
        inline void pop_back()
		{
            tail--;
        }
        inline void pop()
		{
            head++;
        }
        inline int front()
		{
            return a[head];
        }
        inline int back()
		{
            return a[tail-1];
        }
        inline bool empty()
		{
            return head>=tail;
        }
    private:
        int head,tail,a[10000000];
}q;

int n,m,s,t,cnt=1,tot=1,in[N][N],out[N][N],head[M],to[M],c[M],nxt[M],num[M];
int fx[]={-1,0,1,0},fy[]={0,1,0,-1};

inline void adde(int u,int v,int ci)
{
	++cnt;
	to[cnt]=v;
	c[cnt]=ci;
	nxt[cnt]=head[u];
	head[u]=cnt;
	
	++cnt;
	to[cnt]=u;
	c[cnt]=0;
	nxt[cnt]=head[v];
	head[v]=cnt;
}
inline bool add_num()
{
	memset(num,0,sizeof(num)); 
	num[s]=1;
	q.push(s);
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(register int i=head[u];i;i=nxt[i])
		{
			if(!num[to[i]]&&c[i])
			{
				num[to[i]]=num[u]+1;
				q.push(to[i]);
			}
		}
	}
	return num[t];
}

inline int dfs(int u,int minflow)
{
	if(u==t)return minflow;
	for(register int i=head[u];i;i=nxt[i])
	{
		int minn;
		if(c[i]&&num[to[i]]==num[u]+1&&(minn=dfs(to[i],min(c[i],minflow))))
		{
			c[i]-=minn;
			c[i^1]+=minn;
			return minn;
		}
	}
	return 0;
}

inline int dinic()
{
	int ans=0;
	while(add_num())
	{
		int maxflow;
		while((maxflow=dfs(s,INF)))ans+=maxflow;
	}
	return ans;
}

inline int read()
{
	int x=0;
	char ch=getchar();
	while(ch<'0'||ch>'9')ch=getchar();
	while(ch>='0'&&ch<='9')
	{
		x=(x<<1)+(x<<3)+(ch^'0');
		ch=getchar();
	}
	return x;
}

int main()
{
//	freopen("a.txt","r",stdin);
	n=read();m=read();
	s=1,t=1+n*n*2+1;
	for(register int i=1;i<=n;++i) 
	{
		for(register int j=1;j<=n;++j) 
		{
			in[i][j]=++tot,out[i][j]=++tot;
			adde(in[i][j],out[i][j],1);
		}
	}
	for(register int i=2;i<n;++i)
	{
		adde(out[1][i],t,1);
		adde(out[n][i],t,1);
	}
	for(register int i=2;i<n;++i)
	{
		adde(out[i][1],t,1);
		adde(out[i][n],t,1);
	}
	adde(out[1][1],t,1);
	adde(out[1][n],t,1);
	adde(out[n][1],t,1);
	adde(out[n][n],t,1);
	int x,y;
	int t = m;
	while(m--)
	{
		x=read();y=read();
		adde(s,in[x][y],1);
	}
	for(register int i=1;i<=n;++i) 
	{
		for(register int j=1;j<=n;++j)
		{
			for(register int k=0;k<4;++k)
			{
				int xi=i+fx[k],yi=j+fy[k];
				if(xi>=1&&xi<=n&&yi>=1&&yi<=n)adde(out[i][j],in[xi][yi],1);
			} 
		}
	} 
	if(dinic()==t)puts("YES");
	else puts("NO");
	return 0;
}
2020/5/9 11:44
加载中...