您的位置:首页 > 其它

bzoj2756 [SCOI2012]奇怪的游戏

2016-07-12 15:30 375 查看
 题解可能因为比较懒,所以不会写太多。但是好题还是要写一下的。

  题意不说了。 做法很巧妙,要对总和进行分析。

  硕神分析的很不错,他那里也有黄学长的链接,去那里看看吧。点击打开链接 

  我放个代码给你看看就好。。

   

#include
#include
#include
#include
#include
#include
#include
#include
#define Max (1ll<<50)
#define me(a,x) memset(a,x,sizeof a)
#define cp(a,x) memcpy(a,x,sizeof a)
using namespace std;
typedef long long LL;
const int dx[4]={1,-1,0,0};
const int dy[4]={0,0,1,-1};
struct node
{
int x,y,next; LL c;
}a[21000]; int len,first[2010];
void ins(int x,int y,LL c)
{
a[++len].x=x,a[len].y=y,a[len].c=c;
a[len].next=first[x],first[x]=len;
a[++len].x=y,a[len].y=x,a[len].c=0;
a[len].next=first[y],first[y]=len;
}
queueq;
int h[2010],t;
bool spfa()
{
for(int i=0;i<=t;i++)h[i]=0;
h[0]=1; q.push(0);
while(!q.empty())
{
int x=q.front();
q.pop();
for(int k=first[x];k;k=a[k].next)
{
int y=a[k].y;
if(!h[y] && a[k].c)
h[y]=h[x]+1 , q.push(y);
}
}
return h[t]>0;
}
LL dfs(int x,LL f)
{
if(x==t)return f;
LL de=0;
for(int k=first[x];k;k=a[k].next)
{
int y=a[k].y;
if(a[k].c && h[y]==h[x]+1)
{
LL mf=dfs(y,min(a[k].c,f-de));
a[k].c-=mf,a[k^1].c+=mf,de+=mf;
if(de==f)return f;
}
}
if(!de)h[x]=0;
return de;
}
int n,m;
LL tot,p[45][45];
LL dicnic()
{
LL s=0;
while(spfa())s+=dfs(0,Max);
return s;
}
bool check(LL x)
{
len=1; me(first,0); tot=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
int u=(i-1)*m+j;
if((i+j)&1)
{
ins(0,u,x-p[i][j]); tot+=x-p[i][j];
for(int k=0;k<4;k++)
{
int x=i+dx[k],y=j+dy[k];
if(x<1||y<1||x>n||y>m)continue;
ins(u,(x-1)*m+y,Max);
}
}
else ins(u,t,x-p[i][j]);
}
if(dicnic()==tot)return 1;
return 0;
}
int main()
{
int i,j,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m); t=n*m+1;
int c0=0,c1=0; LL l=0,r=Max,s0=0,s1=0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
scanf("%I64d",&p[i][j]);
l=max(l,p[i][j]);
if((i+j)&1) c1++,s1+=p[i][j];
else c0++,s0+=p[i][j];
}
if(c0!=c1)
{
LL x=(s0-s1)/(c0-c1);
if(x>=l)
if(check(x))
{
printf("%lld\n",x*c1-s1);
continue;
}
printf("-1\n");
}
else
{
LL ans;
if(s0!=s1)
{
printf("-1\n");
continue;
}
while(l<=r)
{
LL mid=(l+r)>>1;
if(check(mid)){ans=mid; r=mid-1;}
else l=mid+1;
}
printf("%lld\n",ans*c1-s1);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: