hihocoder1426||UVALive - 7672 What a Ridiculous Election

https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=5694

16北京现场赛题目

题意:

每次有三种可行操作

1:交换相邻两个数位

2:把某一个数位加1,取模10

3:把某一个数位乘2,取模10

2操作最多能用3次,3操作最多能用2次

给一个五个字符的字符串,问12345最少要几次操作后得到给的字符串

搜索预处理一下就可以了,起初想法就是,因为交换数位并不影响2,3操作,所以先BFS预处理12345只进行1操作后到达每个状态的最少操作次数

然后在从这每个状态向下暴力2,3操作就可以了

自己埋了个坑。。。。。。

一直用一个dp数组记录的,因此BFS预处理的那些状态的值可能会因为第二步暴力时改变,这样显然不可以,因为没有记录暴力改变已经用掉的2,3操作的次数

开个vector暂存一下BFS处理出来的即可

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
int dp[200000];
int a[6],b[6];
struct node
{
	int state,cnt;
};
void BFS()
{
	node now;
	now.state=12345,now.cnt=dp[12345]=0;
	queue<node>Q;
	Q.push(now);
	while(!Q.empty())
	{
		node pe=Q.front();
		Q.pop();
		int i,k,temp=pe.state;
		for(i=0;i<5;i++)
		{
			a[i]=temp%10;
			temp/=10;
		}
		for(i=0;i<5;i++)
		b[i]=a[i];
		for(i=0;i<4;i++)
		{
				swap(b[i],b[i+1]);
				int now=0,t=1;
				for(k=0;k<5;k++)
				now+=t*b[k],t*=10;
				if(dp[now]==inf)
				{
					node ne;
					ne.state=now;
					dp[now]=pe.cnt+1;
					ne.cnt=pe.cnt+1;
					Q.push(ne);
				}
				swap(b[i],b[i+1]);
		}
	}
}
char ch[6];
int need;
void dfs(int state,int l1,int l2,int cost)
{
    dp[state]=min(dp[state],need+cost);
    if(l1==0&&l2==0)
    return ;
    int st=state,t=1;
    for(int i=4;i>=0;i--)
    {
            int temp=st%10;
            if(l1)
            dfs(state-temp*t+(temp+1)%10*t,l1-1,l2,cost+1);
            if(l2)
            dfs(state-temp*t+(temp*2)%10*t,l1,l2-1,cost+1);
            st/=10;
            t*=10;
    }
    return ;
}
vector<node>w;
int main()
{
	memset(dp,inf,sizeof(dp));
	BFS();
	for(int i=1;i<100000;i++)
	if(dp[i]!=inf)
	{
            node temp;
            temp.state=i,temp.cnt=dp[i];
            w.push_back(temp);
	}
        for(int i=0;i<w.size();i++)
        need=w[i].cnt,dfs(w[i].state,3,2,0);
	while(~scanf("%s",ch))
	{
		int state=0,t=1;
		for(int i=4;i>=0;i--)
		{
			state+=(ch[i]-'0')*t,t*=10;
		}
		if(dp[state]==inf)
		printf("-1\n");
		else
		printf("%d\n",dp[state]);
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值