只能求神牛帮忙了,zoj 1204 优先队列+BFS 爆内存 求解决!该如何解决
只能求神牛帮忙了,zoj 1204 优先队列+BFS 爆内存 求解决!
直接贴代码,坐等大牛出没:
这题我已经用DFS A了!想试试BFS怎么过!想了很久不想放弃!
#include <queue>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
struct node
{
bool operator < (const node tmp) const{
if(store == tmp.store) {if(b[0]>tmp.b[0]) return b[0]>tmp.b[0];}
else return store > tmp.store;
}
short int cur;
int sum;
int b[15];
short int store;
};
priority_queue <node> equ;
int a[30],cot,n;
int cmp(const void *a,const void *b)
{
return (*(int* )a - *(int* )b) ;//return(*(int *)a-*(int *)b);
}
void bfs()
{
int i,l = 1;
node r;
r.cur = 0;
r.sum = a[0];
r.b[0] = a[0];
r.store = 1;
equ.push(r);
node temp ,temp1;
while(!equ.empty())
{
temp = equ.top();temp1 = temp;
equ.pop();
for(i = temp.cur+1;i < n; i++)
{
if(temp.sum <= a[n-1]){
temp.cur = i;
temp.sum += a[i];
temp.b[temp.store++] = a[i];
equ.push(temp);
for(int j = 2;j < n;j ++)
{
if(temp.sum == a[j])
{
cot ++;
printf("%d",temp.b[0]);
for(int k = 1;k < temp.store;k++)
printf("+%d",temp.b[k]);
printf("=%d\n",temp.sum);
}
}
temp = temp1;
}
}
if(l<n - 1){
r.cur = l;
r.sum = a[l];
r.b[0] = a[l];
r.store = 1;
equ.push(r);
l++;
}
}
}
int main()
{
int cas,i;
scanf("%d",&cas);
while(cas --)
{
scanf("%d",&n);
for(i = 0;i < n;i ++)
{
scanf("%d",&a[i]);
}
qsort(a,n,sizeof(a[0]),cmp);
cot = 0;
bfs();
if(cot == 0) printf("Can't find any equations.\n");
printf("\n");
}
}
------解决方案--------------------
直接贴代码,坐等大牛出没:
这题我已经用DFS A了!想试试BFS怎么过!想了很久不想放弃!
#include <queue>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
struct node
{
bool operator < (const node tmp) const{
if(store == tmp.store) {if(b[0]>tmp.b[0]) return b[0]>tmp.b[0];}
else return store > tmp.store;
}
short int cur;
int sum;
int b[15];
short int store;
};
priority_queue <node> equ;
int a[30],cot,n;
int cmp(const void *a,const void *b)
{
return (*(int* )a - *(int* )b) ;//return(*(int *)a-*(int *)b);
}
void bfs()
{
int i,l = 1;
node r;
r.cur = 0;
r.sum = a[0];
r.b[0] = a[0];
r.store = 1;
equ.push(r);
node temp ,temp1;
while(!equ.empty())
{
temp = equ.top();temp1 = temp;
equ.pop();
for(i = temp.cur+1;i < n; i++)
{
if(temp.sum <= a[n-1]){
temp.cur = i;
temp.sum += a[i];
temp.b[temp.store++] = a[i];
equ.push(temp);
for(int j = 2;j < n;j ++)
{
if(temp.sum == a[j])
{
cot ++;
printf("%d",temp.b[0]);
for(int k = 1;k < temp.store;k++)
printf("+%d",temp.b[k]);
printf("=%d\n",temp.sum);
}
}
temp = temp1;
}
}
if(l<n - 1){
r.cur = l;
r.sum = a[l];
r.b[0] = a[l];
r.store = 1;
equ.push(r);
l++;
}
}
}
int main()
{
int cas,i;
scanf("%d",&cas);
while(cas --)
{
scanf("%d",&n);
for(i = 0;i < n;i ++)
{
scanf("%d",&a[i]);
}
qsort(a,n,sizeof(a[0]),cmp);
cot = 0;
bfs();
if(cot == 0) printf("Can't find any equations.\n");
printf("\n");
}
}
------解决方案--------------------