2017南宁网络赛J.Minimum Distance in a Star Graph(bfs求最短路)
2017-09-28 09:50
405 查看
题意:
给你一个n维空间,有n!的节点,节点编号为n的全排列,每个节点num与n-1个节点相连(这n-1个节点的编号分别为num的第一位与后面n-1位交换的数,例如1234与2134,3214,4231相连)
思路:
bfs求最短路,由于节点的数比较大,用map离散化节点就好了。最好根据题意模拟一下相连的边。
代码:
给你一个n维空间,有n!的节点,节点编号为n的全排列,每个节点num与n-1个节点相连(这n-1个节点的编号分别为num的第一位与后面n-1位交换的数,例如1234与2134,3214,4231相连)
思路:
bfs求最短路,由于节点的数比较大,用map离散化节点就好了。最好根据题意模拟一下相连的边。
代码:
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll,int> pii; map<ll,int> mp; ll Qpow(ll x,ll n) { ll res = 1; while(n>0) { if(n&1) res = res*x; x = x*x; n>>=1; } return res; } int main() { int n; cin>>n; int test = 5; while(test--) { ll st,en; scanf("%lld%lld",&st,&en); queue<pii> q; mp.clear(); q.push(make_pair(st,0)); mp[st]++; int ans = 0; while(!q.empty()) { pii p = q.front(); ll num = p.first; if(num==en) { ans = p.second; break; } q.pop(); ll top = num/Qpow(10,n-1); ll temp = num; for(int i = 0;i<n-1;i++) { ll bac = temp%10; temp /= 10; ll now = num-top*Qpow(10,n-1)-bac*Qpow(10,i); now += bac*Qpow(10,n-1)+top*Qpow(10,i); if(!mp[now]) { mp[now]++; q.push(make_pair(now,p.second+1)); } } } printf("%d\n",ans); } return 0; }
相关文章推荐
- 2017 ACM-ICPC南宁网络赛: J. Minimum Distance in a Star Graph(BFS)
- 2017 icpc 南宁赛区 J. Minimum Distance in a Star Graph(bfs)
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 J.Minimum Distance in a Star Graph
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛(J.Minimum Distance in a Star Graph)
- 2017ICPC南宁赛区网络赛 Minimum Distance in a Star Graph (bfs)
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛- J. Minimum Distance in a Star Graph
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 J Minimum Distance in a Star Graph 广度优先搜索
- 计蒜客 Minimum Distance in a Star Graph 2017icpc南宁赛区 字符串bfs
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 J. Minimum Distance in a Star Graph
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 Minimum Distance in a Star Graph
- Minimum Distance in a Star Graph BFS/康托展开 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 J. Minimum Distance in a Star Graph(bfs+状态保存)
- Minimum Distance in a Star Graph(南宁网络赛)
- ???Minimum Distance in a Star Graph
- 计蒜客 Minimum Distance in a Star Graph 思维水题
- Minimum Distance in a Star Graph
- HDU 4725 The Shortest Path in Nya Graph 【最短路之建图难点】
- hdu5876 Sparse Graph -补图的最短路-bfs
- HDU 4725 The Shortest Path in Nya Graph(拆点+最短路)
- 【最短路】 HDU 4725 The Shortest Path in Nya Graph