poj 1564 && zoj 1711 Sum It Up (dfs)
2012-03-11 21:13
441 查看
http://poj.org/problem?id=1564
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1711
简单深搜,主要是这一句 if(!vis[i]&&data[i]<=sum&&(data[i]!=data[i-1]||i==pos))。
确保两个连续的相同的数只有一次机会进入ans[],避免了结果的重复。
code:
#include<cstdio>
#include<cstring>
int data[15] ;
int ans[15] ;
bool vis[15] ;
bool flag ;
int n ;
void dfs(int sum, int count, int pos){
if(!sum){
flag = true ;
printf("%d", ans[0]) ;
for(int i=1; i<count; i++)
printf("+%d", ans[i]) ;
printf("\n") ;
return ;
}
for(int i=pos; i<n; i++){
if(!vis[i]&&data[i]<=sum&&(data[i]!=data[i-1]||i==pos)){
vis[i] = true ;
ans[count] = data[i] ;
dfs(sum-data[i], count+1, i+1) ;
vis[i] = false ;
}
}
}
int main(){
int t, i, j ;
while(~scanf("%d%d", &t, &n)&&t+n){
memset(vis, false, sizeof(vis)) ;
for(i=0; i<n; i++){
scanf("%d", &data[i]) ;
if(data[i]>t) vis[i] = true ;
}
printf("Sums of %d:\n", t) ;
flag = false ;
dfs(t, 0, 0) ;
if(!flag) printf("NONE\n") ;
}
return 0 ;}
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1711
简单深搜,主要是这一句 if(!vis[i]&&data[i]<=sum&&(data[i]!=data[i-1]||i==pos))。
确保两个连续的相同的数只有一次机会进入ans[],避免了结果的重复。
code:
#include<cstdio>
#include<cstring>
int data[15] ;
int ans[15] ;
bool vis[15] ;
bool flag ;
int n ;
void dfs(int sum, int count, int pos){
if(!sum){
flag = true ;
printf("%d", ans[0]) ;
for(int i=1; i<count; i++)
printf("+%d", ans[i]) ;
printf("\n") ;
return ;
}
for(int i=pos; i<n; i++){
if(!vis[i]&&data[i]<=sum&&(data[i]!=data[i-1]||i==pos)){
vis[i] = true ;
ans[count] = data[i] ;
dfs(sum-data[i], count+1, i+1) ;
vis[i] = false ;
}
}
}
int main(){
int t, i, j ;
while(~scanf("%d%d", &t, &n)&&t+n){
memset(vis, false, sizeof(vis)) ;
for(i=0; i<n; i++){
scanf("%d", &data[i]) ;
if(data[i]>t) vis[i] = true ;
}
printf("Sums of %d:\n", t) ;
flag = false ;
dfs(t, 0, 0) ;
if(!flag) printf("NONE\n") ;
}
return 0 ;}
相关文章推荐
- poj 1564 Sum It Up | zoj 1711 | hdu 1548 (dfs + 剪枝 or 判重)
- zoj 1711 || poj 1564 Sum It Up(DFS~~~去重~)
- ZOJ1711 POJ1564 Sum It Up,DFS+输出排序+去重复
- poj 1564 Sum It Up | zoj 1711 | hdu 1548 (dfs + 剪枝 or 判重)
- POJ 1564 && HDU 1258 Sum It Up(dfs)
- POJ 1564(HDU 1258 ZOJ 1711) Sum It Up(DFS)
- poj 1564 dfs(Sum It Up)
- poj 1564 Sum It Up【dfs+去重】
- 【DFS】poj 1564 Sum It Up(hdu 1258)
- poj 1564 Sum It Up DFS
- POJ 1564 Sum It Up(DFS)
- POJ 1564 Sum It Up(DFS)
- Sum It Up---poj1564(dfs)
- dfs ZOJ 1711 Sum It Up
- Poj 1564 || HDU 1258 Sum It Up(dfs+技巧)
- DFS入门:全排列算法及POJ 1564 Sum it up详解
- poj1564 Sum It Up (zoj 1711 hdu 1258) DFS
- POJ1564 Sum It Up(DFS)
- poj1564 Sum It Up (zoj 1711 hdu 1258) DFS
- POJ 1564 Sum It Up -dfs(回溯法)