【題目描述】
出自 World Final 2015 F. Keyboarding
給定一個 r 行 c 列的在電視上的“虛擬鍵盤”,通過「上,下,左,右,選擇」共 5 個控制鍵,你可以移動電視屏幕上的光標來打印文本。一開始,光標在鍵盤的左上角,每次按方向鍵,光標總是跳到下一個在該方向上與當前位置不同的字符,若不存在則不移動。每次按選擇鍵,則將光標所在位置的字符打印出來。
現在求打印給定文本(要在結尾打印換行符)的最少按鍵次數。
【輸入】
第一行輸入 r,c。
接下來給出一個 r×c 的鍵盤,包括大寫字母,數字,橫線以及星號(星號代表 Enter 換行)。
最后一行是要打印的文本串 S,S 的長度不超過 10000。
【輸出】
輸出打印文本(包括結尾換行符)的最少按鍵次數。保證一定有解。
【輸入樣例】
2 19
ABCDEFGHIJKLMNOPQZY
X*****************Y
AZAZ
【輸出樣例】
19
【提示】
樣例輸入2:
5 20
12233445566778899000
QQWWEERRTTYYUUIIOOPP
-AASSDDFFGGHHJJKKLL*
--ZZXXCCVVBBNNMM--**
ACM-ICPC-WORLD-FINALS-2015
樣例輸出2:
160
樣例輸入3:
6 4
AXYB
BBBB
KLMB
OPQB
DEFB
GHI*
AB
樣例輸出 3
7
數據范圍:
對於 100% 的數據,1≤r,c≤50, S 的長度不超過 10000。
用 vis 記錄訪問時打印字符串的個數,如果當前節點打印個數小於 vis 就無需向下拓展
雙端隊列優化,對於能直接打印字符的節點插入到隊頭,不能直接打印字符的節點插入到隊尾
#include <cstdio>
#include <algorithm>
#include <deque>
#include <cstring>
#include <iostream>
#pragma GCC optimize(1)
using namespace std;
const int N = 10000 + 10;
char f[60][60];
int r, c;
char s[N];
int l;
int vis[60][60];
int ds[55][55][4][3];
struct node
{
int x, y, d;
int step;
};
int dx[4] = {0 , 0, 1, -1};
int dy[4] = {1, -1, 0 , 0};
int ans = 0x7ffffff;
void print(int x)
{
for(int i = 0 ;i < x; i++) printf("%c",s[i]);
printf(" ");
}
void pre()//預處理
{
for(int i = 1; i <= r; i++)
{
for(int j = 1; j <= c; j++)
{
for(int k = 0; k < 4; k++)
{
int x = i, y = j;
while(f[x][y] == f[i][j])
{
x += dx[k];
y += dy[k];
if(x < 0 || y < 0)
{
break;
}
if(!(x > 0 && x <= r && y >0 && y <= c)) break;
}
if(x > 0 && x <= r && y >0 && y <= c)
{
ds[i][j][k][0] = x;
ds[i][j][k][1] = y;
}
}
}
}
}
void bfs()
{
deque <node> q;
q.push_back((node){
1,1,0,0
});
while(q.size())
{
int x = q.front().x;
int y = q.front().y;
int d = q.front().d;
int step = q.front().step;
q.pop_front();
// cout << x <<" "<<y <<" "<<d<<" "<<step<<"\n";
// print(d);
// printf("%c %c\n",f[x][y],s[d]);
if(s[d] == f[x][y]) //在一個位置重復按
{
int cnt = 0;
int p = d;
while(f[x][y] == s[p])
{
cnt++;
p++;
}
d += cnt;
step += cnt;
q.push_front((node){// 插入到隊頭
x,y,d ,step
});
}
if(d == l + 1)
{
printf("%d",step);
return ;
}
for(register int i = 0; i < 4; i++)
{
int xx = ds[x][y][i][0];
int yy = ds[x][y][i][1];
//cout<<xx<<" "<<yy<<"\n";
if(xx > 0 && xx <= r && yy > 0 && yy <= c && vis[xx][yy] < d)
{
vis[xx][yy] = d;
q.push_back((node){
xx,yy,d,step + 1
});//插入到隊尾
}
}
}
}
int main()
{
scanf("%d %d",&r,&c);
getchar();
for(register int i = 1; i <= r; i++)
{
for(register int j = 1; j <= c; j++)
{
f[i][j] = getchar();
}
getchar();
}
scanf("%s",s);
pre();
l = strlen(s);
s[l] = '*';
memset(vis,-1,sizeof(vis));
bfs();
return 0;
}