hdoj1518(搜尋)
阿新 • • 發佈:2019-01-02
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n, a[25], visit[25], side, flag = 0;
bool cmp(int a, int b)
{
return a > b;
}
void dfs(int gs, int len, int k)
{
if (gs >= 3)
{
flag = 1;
return;
}
for (int i = k; i < n; i++)
{
if (flag)
return;
if (visit[i])
continue;
if (len + a[i] == side)
{
visit[i] = 1;
dfs(gs + 1, 0, 0);
visit[i] = 0;
if (flag)
return;
}
else if (len + a[i] < side)
{
visit[i] = 1;
dfs(gs, len + a[i], i + 1);
visit[i] = 0;
if (flag)
return;
}
}
}
int main(int argc, char *argv[])
{
int t, sum;
cin >> t;
while (t--)
{
cin >> n; sum = 0;
for (int i = 0; i<n; i++)
{
cin >> a[i];
sum += a[i];
}
side = sum / 4;
sort(a, a + n, cmp);
if (sum % 4 != 0 || a[0]>side)
{
cout << "no" << endl;
continue;
}
memset(visit, 0, sizeof(visit)); flag = 0;
dfs(0, 0, 0);
if (flag)
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n, a[25], visit[25], side, flag = 0;
bool cmp(int a, int b)
{
return a > b;
}
void dfs(int gs, int len, int k)
{
if (gs >= 3)
{
flag = 1;
return;
}
for (int i = k; i < n; i++)
{
if (flag)
return;
if (visit[i])
continue;
if (len + a[i] == side)
{
visit[i] = 1;
dfs(gs + 1, 0, 0);
visit[i] = 0;
if (flag)
return;
}
else if (len + a[i] < side)
{
visit[i] = 1;
dfs(gs, len + a[i], i + 1);
visit[i] = 0;
if (flag)
return;
}
}
}
int main(int argc, char *argv[])
{
int t, sum;
cin >> t;
while (t--)
{
cin >> n; sum = 0;
for (int i = 0; i<n; i++)
{
cin >> a[i];
sum += a[i];
}
side = sum / 4;
sort(a, a + n, cmp);
if (sum % 4 != 0 || a[0]>side)
{
cout << "no" << endl;
continue;
}
memset(visit, 0, sizeof(visit)); flag = 0;
dfs(0, 0, 0);
if (flag)
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}