问题 J: 爱看电视的LsF
时间限制: 1 秒 内存限制: 64 MB提交: 183 解决: 37
提交 状态
题目描述
LsF(刘师傅)非常喜欢看电视!
不幸的是,遥控器上的一些数字按钮坏了。 但他灵光一闪,如果他不能直接输入他想要看到的频道的号码,那么他可以先输入其他号码,再通过按下按钮+ 和- (这两个按钮由24K钛合金制成,永远不会坏)的方式到达所需的频道。 按钮+将数字增加1,按钮-将数字减少1。当然他依然可以使用那些完好无损的数字按钮输入号码。
他最初在第S频道,他想看第T频道。他想知道由S到T频道所需的最少按钮按压次数。
输入
输入包含多组数据。
对于每组数据,第一行是三个整数n,S,T(n≤10,0≤S,T≤500,000。 第二行是n个数字 a1,a2,...,an,表示数字 ai键已经坏了(0≤ai≤9,ai≠aj when i≠j)。
输出
输入包含多组数据。
对于每组数据,第一行是三个整数n,S,T(n≤10,0≤S,T≤500,000。 第二行是n个数字 a1,a2,...,an,表示数字 ai键已经坏了(0≤ai≤9,ai≠aj when i≠j)。
样例输入
10 1 100
0 1 2 3 4 5 6 7 8 9
9 1 100
0 1 2 3 4 5 6 7 8
样例输出
99
3
队友的广搜
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> #include<queue> using namespace std; struct po{ int x,time; }; char num[10]; int a[11],map[500000]; int dir[2]={-1,1}; int escape,key; int yu(int t){ int i,j,tt=t,k; j=0; if(tt==0){ if(a[0]) return 0; else { key=1;return 1; } } while(tt>0){ num[j]=tt%10; tt/=10; j++; } key=0; for(i=0;i<j;i++){ if(a[num[i]]) return 0; key++; } return 1; } void bfs(po p,int len){ int i; queue<po>que; que.push(p); po hd; if(yu(p.x)){ p.time+=key; if(p.time>=len){ printf("%d\n",len); return ; } printf("%d\n",p.time); return ; } int y; while(!que.empty()){ hd=que.front(); que.pop(); if(hd.time>=len){ printf("%d\n",len); return ; } for(i=0;i<2;i++){ if(hd.x==500000&&!map[499999]){ y=hd.x-1; } else if(hd.x==0&&!map[1]){ y=hd.x+1; } else y=hd.x+dir[i]; if(y<=500000&&y>=0&&!map[y]){ po next; next.x=y; next.time=hd.time+1; if(yu(next.x)){ next.time+=key; if(next.time>=len){ printf("%d\n",len); return ; } printf("%d\n",next.time); return ; } else{ map[next.x]=1; que.push(next); } } } } printf("%d\n",len); return ; } int main(){ int i,n,s,t,q,len; while(~scanf("%d%d%d",&n,&s,&t)){ memset(a,0,sizeof(a)); memset(map,0,sizeof(map)); for(i=0;i<n;i++){ scanf("%d",&q); a[q]=1; } if(s==t){ printf("0\n"); continue; } if(s<t) len=t-s; else len=s-t; po p; p.x=t, p.time=0; map[p.x]=1; bfs(p,len); } return 0; }