BZOJ 2346 Baltic 2011 Lamp SPFA

13 篇文章 0 订阅

题目大意:给定一个电路板,求改变最少的板子数量使电源与灯泡联通

在对角线之间跑最短路,如果需要改变边权就是1,否则就是0

注意别忘了输出NO SOLUTION

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define M 510
using namespace std;
typedef pair<int,int> abcd;
int m,n;
char map[M][M];
abcd heap[M*M];
int f[M][M],pos[M][M],top;
void Push_Up(int t)
{
	while(t>1&&f[heap[t].first][heap[t].second]<f[heap[t>>1].first][heap[t>>1].second])
		swap(heap[t],heap[t>>1]),swap(pos[heap[t].first][heap[t].second],pos[heap[t>>1].first][heap[t>>1].second]),t>>=1;
}
void Insert(abcd x)
{
	heap[++top]=x;
	pos[x.first][x.second]=top;
	Push_Up(top);
}
void Pop()
{
	pos[heap[1].first][heap[1].second]=0;
	heap[1]=heap[top--];
	if(top) pos[heap[1].first][heap[1].second]=1;
	int t=2;
	while(t<=top)
	{
		if(t<top&&f[heap[t+1].first][heap[t+1].second]<f[heap[t].first][heap[t].second])
			++t;
		if(f[heap[t].first][heap[t].second]<f[heap[t>>1].first][heap[t>>1].second])
			swap(heap[t],heap[t>>1]),swap(pos[heap[t].first][heap[t].second],pos[heap[t>>1].first][heap[t>>1].second]),t<<=1;
		else
			break;
	}
}
const int dx[]={-1,-1,1,1};
const int dy[]={-1,1,-1,1};
const int posx[]={0,0,1,1};
const int posy[]={0,1,0,1};
const char wire[]={'\\','/','/','\\'};
void SPFA()
{
	int i;
	memset(f,0x3f,sizeof f);
	f[0][0]=0;
	Insert( abcd(0,0) );
	while(top)
	{
		abcd x=heap[1];Pop();
		for(i=0;i<4;i++)
		{
			int xx=x.first+dx[i];
			int yy=x.second+dy[i];
			int posxx=x.first+posx[i];
			int posyy=x.second+posy[i];
			if(xx<0||yy<0||xx>m||yy>n)
				continue;
			if(f[xx][yy]>f[x.first][x.second]+(map[posxx][posyy]!=wire[i]) )
			{
				f[xx][yy]=f[x.first][x.second]+(map[posxx][posyy]!=wire[i]);
				if(!pos[xx][yy])
					Insert( abcd(xx,yy) );
				else
					Push_Up(pos[xx][yy]);
			}
		}
	}
}
int main()
{
	int i,j;
	cin>>m>>n;
	for(i=1;i<=m;i++)
		scanf("%s",map[i]+1);
	SPFA();
	if(f[m][n]==0x3f3f3f3f)
		puts("NO SOLUTION");
	else
		cout<<f[m][n]<<endl;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值