2017 ACM-ICPC 南宁区比赛 Minimum Distance in a Star Graph

2017-09-25 19:58:04

writer:pprp

题意看上去很难很难,但是耐心看看还是能看懂的,给你n位数字

你可以交换第一位和之后的某一位,问你采用最少的步数可以交换成目标

有五组数据

用BFS进行搜索,并进行剪枝,已经搜索过的点不再搜索

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <set>
#include <queue> using namespace std; string sa, sb; int n; struct node
{
string str;
int times;
node()
{
str = "";
times = ;
}
}; int bfs()
{
queue<node> q;
set<string> ss;
node now , nex;
now.str = sa;
q.push(now);
ss.insert(now.str);
while(!q.empty())
{
now = q.front();
q.pop();
if(now.str == sb)
return now.times;
for(int i = ; i < n;i++)
{
nex.str = now.str;
nex.times = now.times+;
nex.str[i] = now.str[];
nex.str[] = now.str[i];
if(ss.count(nex.str) == )
{
ss.insert(nex.str);
q.push(nex);
}
else
continue;
}
}
} int main()
{
cin >> n;
for(int i = ; i < ;i++)
{
cin >> sa >> sb;
cout << bfs() << endl;
} return ;
}

现阶段掌握搜索还不是太好,希望以后可以尽快掌握

上一篇:破损的键盘(UVa 11988)


下一篇:caret彻底的理解css的三角形【通过border】