求助 TLE
查看原帖
求助 TLE
369181
bamboo12345楼主2023/11/30 19:20

rt,好像最后一个点跑的特别特别慢,求大佬帮助

#include <bits/stdc++.h>
using namespace std;
const int maxn=55,maxm=3e6+5;
int n,m,k;
int head[maxm],to[maxm],nxt[maxm],val[maxm],tot=1, cur[maxm], cnt;
void add(int x,int y,int w)
{
	to[++tot]=y;
	val[tot]=w;
	nxt[tot]=head[x];
	head[x]=tot;
}
int dep[maxm],gap[maxm],t;
void bfs()
{
	queue<int> q;
	q.push(t); 
	memset(dep,-1,sizeof(dep));
	memset(gap,0,sizeof(gap));
	dep[t]=0;
	gap[dep[t]]++;
	while(!q.empty())
	{
		int tmp=q.front();
		q.pop();
		for(int i=head[tmp];i;i=nxt[i])
		{
			
			if(dep[to[i]]==-1)
			{
			//	cout <<tmp<<" "<<to[i]<<" "<<val[i]<<" "<<2<<endl;
				dep[to[i]]=dep[tmp]+1;
				gap[dep[to[i]]]++;
				q.push(to[i]);
			}
		}
	}
}
int maxflow=0,s=0;
int dfs(int now,int flow)
{
	//cout <<now<<endl;
	if(!flow)
		return 0;
	if(now==t)
	{
		maxflow+=flow;
		return flow;
	}
	int use=0;
	for(int i=cur[now];i;i=nxt[i])
	{
		//cout <<now<<" "<<to[i]<<endl;
		cur[now] = i;
		if(dep[to[i]]+1==dep[now])
		{
			int f=dfs(to[i],min(flow-use,val[i]));
			val[i]-=f,val[i^1]+=f,use+=f;
			if(use==flow)	
				return use;
		}
	}
//	cout <<s<<endl;
	if(--gap[dep[now]]==0)
		dep[s]=cnt+1;
	dep[now]++;
	gap[dep[now]]++;
	return use;
}
void isap()
{
	bfs();
	while(dep[s]<cnt+1)
	{
		memcpy(cur, head, sizeof(cur));
	//	cout <<s<<endl;
		dfs(s,0x3f3f3f3f);
	//	cout <<s<<endl;
	}
}
int l[maxn][maxn],r[maxn],pre[maxn],h[maxn];
int find(int x)
{
	return (pre[x]==x?x:pre[x]=find(pre[x]));
}
int main()
{
//	freopen("P2754_11.in", "r", stdin);
//	freopen("test.out", "w", stdout);
	cin >>n>>m>>k;
	s=0;
	for(int i=1;i<=n+2;i++)
		pre[i]=i;
	for(int i=1;i<=m;i++)
	{
		//cout <<i<<endl;
		cin >>h[i]>>r[i];
		for(int j=0;j<r[i];j++)
		{
			cin >>l[i][j];
			if(l[i][j]==0)
				l[i][j]=n+1;
			if(l[i][j]==-1)
				l[i][j]=n+2;
		}
		for(int j=1;j<r[i];j++)
			pre[find(l[i][j - 1])]=find(l[i][j]);
	//	for(int j=1;j<=n+2;j++)
	//		cout <<pre[j]<<endl;
	}
	
	if(find(n+1)!=find(n+2))
	{
		cout <<0<<endl;
		return 0;
	}
	//cout <<endl;
	t=maxm-2;
	for(int i=1;;i++)
	{
		cout << i << endl;
	//	cout <<i<<endl<<endl<<endl;
		cnt = i * (n + 1) + (n + 1) + 10;
		add(s,(i-1)*(n + 1)+(n + 1),0x3f3f3f3f);
		add((i-1)*(n + 1)+(n + 1),s,0);
	//	cout <<s<<" "<<s<<" "<<(i-1)*n+n<<endl;
		for(int j=1;j<=m;j++)
		{
			int t1=(i-1)%r[j],t2=(i-0)%r[j];
			t1=l[j][t1],t2=l[j][t2];
			if(t1!=n+2)
				t1=(i-1)*(n + 1)+t1;
			else
				t1=t;
			if(t2!=n+2)
				t2=i*(n + 1)+t2;
			else
				t2=t;
			//cout <<t1<<" "<<t2<<endl;
			add(t1,t2,h[j]);
			add(t2,t1,0);
		}
		isap();
	//	cout <<maxflow<<endl;
		if(maxflow>=k)
		{
			cout <<i<<endl;
			return 0;
		}
		for(int j=1;j<=n + 1;j++)
			add((i-1)*(n + 1)+j,i*(n + 1)+j,0x3f3f3f3f),add(i*(n + 1)+j,(i-1)*(n + 1)+j,0);
	}
	
	return 0;
}
2023/11/30 19:20
加载中...