http://acm.hdu.edu.cn/showproblem.php?pid=4337&&dfs
2012-08-03 14:37
260 查看
一道深搜题,给你一些朋友的关系,让你找到这样的一个排列,相邻的人是朋友,,
AC代码:
#include<cstdio>
#include<string.h>
#include<string>
#define N 180
using namespace std;
bool map
,vis
;
int path
;
bool flag;
int n,m,res;
void dfs(int x)
{
if(flag) return;
if(res==n)
{
printf("1");
for(int i=1;i<n;++i)
printf(" %d",path[i]);
printf("\n");
flag=true;
return;
}
for(int i=2;i<=n;++i)
if(!vis[i]&&map[x][i])
{
if(res==n-1&&!map[i][1]) continue;
path[res]=i;
vis[i]=true;
++res;
dfs(i);
vis[i]=false;
--res;
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(map,false,sizeof(map));
memset(vis,false,sizeof(vis));
for(int i=0;i!=m;++i)
{
int a,b;
scanf("%d%d",&a,&b);
map[a][b]=map[b][a]=1;
}
res=1,flag=false;
vis[1]=true;
dfs(1);
if(!flag) printf("no solution\n");
}return 0;
}
AC代码:
#include<cstdio>
#include<string.h>
#include<string>
#define N 180
using namespace std;
bool map
,vis
;
int path
;
bool flag;
int n,m,res;
void dfs(int x)
{
if(flag) return;
if(res==n)
{
printf("1");
for(int i=1;i<n;++i)
printf(" %d",path[i]);
printf("\n");
flag=true;
return;
}
for(int i=2;i<=n;++i)
if(!vis[i]&&map[x][i])
{
if(res==n-1&&!map[i][1]) continue;
path[res]=i;
vis[i]=true;
++res;
dfs(i);
vis[i]=false;
--res;
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(map,false,sizeof(map));
memset(vis,false,sizeof(vis));
for(int i=0;i!=m;++i)
{
int a,b;
scanf("%d%d",&a,&b);
map[a][b]=map[b][a]=1;
}
res=1,flag=false;
vis[1]=true;
dfs(1);
if(!flag) printf("no solution\n");
}return 0;
}
相关文章推荐
- http://acm.hdu.edu.cn/showproblem.php?pid=1106&&排序
- http://acm.hdu.edu.cn/showproblem.php?pid=1023&&卡特兰数
- http://acm.hdu.edu.cn/showproblem.php?pid=3790&&最短路径问题
- I NEED A OFFER! &&http://acm.hdu.edu.cn/showproblem.php?pid=1203
- http://acm.hdu.edu.cn/showproblem.php?pid=1878&&欧拉回路
- http://acm.hdu.edu.cn/showproblem.php?pid=2688&&树状数组求正序数
- Red and Black&&http://acm.hdu.edu.cn/showproblem.php?pid=1312
- http://acm.hdu.edu.cn/showproblem.php?pid=1171&&0-1&&多重背包混合
- http://acm.hdu.edu.cn/showproblem.php?pid=2066&&多源多点
- A/B&&http://acm.hdu.edu.cn/showproblem.php?pid=1576
- 找规律。。&&http://acm.hdu.edu.cn/showproblem.php?pid=1097
- http://acm.hdu.edu.cn/showproblem.php?pid=2199&&二分查找求高次方程的根
- http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?pid=1004&ojid=1&cid=6866&hide=1&problem=Pro
- http://acm.hdu.edu.cn/showproblem.php?pid=3549&&ISAP
- HDU Today&&http://acm.hdu.edu.cn/showproblem.php?pid=2112
- http://acm.hdu.edu.cn/showproblem.php?pid=1059&&多重背包
- 最大连续子序列&&http://acm.hdu.edu.cn/showproblem.php?pid=1231
- 树状数组&&http://acm.hdu.edu.cn/showproblem.php?pid=1556
- http://acm.hdu.edu.cn/showproblem.php?pid=1166&&线段树区间求和
- http://acm.hdu.edu.cn/showproblem.php?pid=2642&&二维树状数组