您的位置:首页 > 其它

dfs ZOJ 1711 Sum It Up

2010-09-10 19:38 399 查看
这几天学,BFS和DFS算法,参照网上找的程序,对照着写的。

所有的排列组合问题,基本是基于DFS算法的思路而来的

Sum It Up

#include<iostream>
using namespace std;

int t;
int n;
int num[12];
int rcd[12];
int usedtimes[12];
int differentnums;
bool isfind = false;
void norepeat_combination(int, int);
void print(int);
int main()
{
int count = 0;
int a;
bool flag;
//freopen("test.txt","r",stdin);
while (cin >> t >> n && !(t==0 && n == 0) )
{
for (int i = 0; i < n; i++)
{
usedtimes[i] = 1;
}
flag = true;
for (int i = 0; i < n; i++)
{
cin >> a;
for (int j = 0; j < count; j++ )
{
if (a == num[j])
{
flag = false;
usedtimes[j]++;
}
}
if (flag)
{
num[count] = a;
count++;

}
flag = true;
}

n = count;
cout << "Sums of " << t << ":" << endl;
norepeat_combination(0, 0);
if (!isfind)
{
cout << "NONE" << endl;
}
isfind = false;
count = 0;
}
return 0;
}
int sum;

//生成不重复组合,类似DFS过程
void norepeat_combination(int len, int current)
{
sum = 0;
for (int i = 0; i < len; i++)
{
sum += rcd[i];
}
if (sum == t)
{
isfind = true;
print(len);
}
else
{
for (int i = current; i < n; i++)
{
if (usedtimes[i])
{
usedtimes[i]--;
rcd[len] = num[i];
norepeat_combination(len+1, i);//这里不是i+1,要把所有重复的都用完,才填入下一个不同的数字
usedtimes[i]++;
}
}
}

}

void print(int len)
{
for (int i = 0; i < len; i++)
{
cout << rcd[i];
if (i != len - 1)
{
cout << "+";
}
}
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: