南阳理工学院 擅长排列的小明
2018-01-29 17:18
417 查看
一开始没想出来,后来发现需要用到stl的一个函数,或者需要使用深度优先搜索的方法,这两者都是自己的知识盲点,故首先参考了这篇博客 http://blog.csdn.net/whjkm/article/details/38498317 以及百度了深度优先搜索的相关内容,发现dfs的本质实际上是递归+回溯。其代码的实现思路为:
DFS(顶点v)
{
标记v为已遍历;
for(对于每一个邻接v切未标记遍历的店u)
DFS(u);
}故需要一个标记数组,表示每个点是否被访问过。
附AC代码之dfs:
另通过本题的学习,明白了在使用递归函数时,当本层执行完毕时,会自动回溯返回上一层,无需添加代码中注释的return。
AC代码之STL之next_permutation(a.begin(),a.end())函数:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int N;//n,m;
// string s1,s2;???(1)
scanf("%d",&N);
while(N--)
{
int n,m;
string s1,s2;//???(2)
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
s1+='0'+i;
}
s2=s1.substr(0,m);
cout<<s2<<endl;
while(next_permutation(s1.begin(),s1.end()))
{
if(s2!=s1.substr(0,m))
{
s2=s1.substr(0,m);
cout<<s2<<endl;
}
}
}
return 0;
}next_permutation(a.begin(),a.end())函数:实现字符串a按字典序的全排列。
具体原理等可参考博客:http://www.cnblogs.com/mycapple/archive/2012/08/13/2635853.html
通过本题的学习,发现cin,cout比scanf,printf慢,在越小范围内定义变量越快。(见???(1)处和???(2)处)
4000
DFS(顶点v)
{
标记v为已遍历;
for(对于每一个邻接v切未标记遍历的店u)
DFS(u);
}故需要一个标记数组,表示每个点是否被访问过。
附AC代码之dfs:
#include<cstdio> #include<cstring> int visit[10]; int ans[10]; using namespace std; void dfs(int pos,int n,int m) { if(pos==m) { for(int i=0;i<m;i++) { printf("%d",ans[i]); } printf("\n"); } else { for(int i=1;i<=n;i++) { if(!visit[i]) { visit[i]=1; ans[pos]=i; dfs(pos+1,n,m); visit[i]=0; } } } //return ; } int main() { int N,n,m; scanf("%d",&N); while(N--) { scanf("%d%d",&n,&m); memset(visit,0,sizeof(visit)); dfs(0,n,m); } return 0; }
另通过本题的学习,明白了在使用递归函数时,当本层执行完毕时,会自动回溯返回上一层,无需添加代码中注释的return。
AC代码之STL之next_permutation(a.begin(),a.end())函数:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int N;//n,m;
// string s1,s2;???(1)
scanf("%d",&N);
while(N--)
{
int n,m;
string s1,s2;//???(2)
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
s1+='0'+i;
}
s2=s1.substr(0,m);
cout<<s2<<endl;
while(next_permutation(s1.begin(),s1.end()))
{
if(s2!=s1.substr(0,m))
{
s2=s1.substr(0,m);
cout<<s2<<endl;
}
}
}
return 0;
}next_permutation(a.begin(),a.end())函数:实现字符串a按字典序的全排列。
具体原理等可参考博客:http://www.cnblogs.com/mycapple/archive/2012/08/13/2635853.html
通过本题的学习,发现cin,cout比scanf,printf慢,在越小范围内定义变量越快。(见???(1)处和???(2)处)
4000
相关文章推荐
- 南阳理工学院OJ 擅长排列的小明
- 擅长排列的小明
- nyoj19 擅长排列的小明
- 擅长排列的小明
- 擅长排列的小明 II
- nyoj19 擅长排列的小明 (排列组合)
- nyoj-19-擅长排列的小明
- 擅长排列的小明
- nyoj 19擅长排列的小明 (DFS)
- NYOJ 19-擅长排列的小明
- NYOJ--19--擅长排列的小明
- nyoj 19 擅长排列的小明
- 擅长排列的小明 II(nyoj 469)
- (STL) ACM_擅长排列的小明.(补)
- NYOJ 19 擅长排列的小明
- NYOJ 题目19 擅长排列的小明(dfs)
- nyoj469 擅长排列的小明 II
- nyoj19擅长排列的小明(STL)&&(DFS)
- 擅长排列的小明 II
- NYOJ 469 擅长排列的小明 II (dp问题)