問題:給你三行數據,每行數據有L,N,M個數據,從每一行數據中找一個數相加的和等於你要求的數,有則輸出YES,否則輸出NO。
思考:看到這個問題後發現數據量蠻大的,而且是只要找到存在的,發現只要找存在就想到了深搜(DFS),但是發現搜索樹好像蠻大的,而且搜索的數據量也很大,每個搜
一次就很龐大了。
所以,用常規深搜剪枝一直都比較麻煩,很多不容易想到而導致超時。老師在昨天晚上就講了很多剪枝的地方:
1、找到三行裡面最小和最大和,首先判斷要求的和是否在這個區間內。
2、找到數據後就不用再搜了直接退出並輸出,進行下一個搜索。
3、對那三行數據各自從小到大排序,並把每行裡面重復的數據刪掉,因為只要在每行找一個數就行。同理,在判斷要求的數中,如果有相同的和也可以忽略掉,直接輸出。
等等很多。。
後面我們又想到了用哈希表來存儲,這樣時間會很短,但是發現哈希數組要開的很大,由於內存限制而無法滿足要求,所以放棄。
今天早上我突然又想到了用容器(STL)map,這個是個好東西,它的功能和哈希很相似,但是開辟的內存不需要哈希那麼多。應該可以解決內存限制問題。我轉載有一些
關於STL的資料,可以點擊 這裡
但是交的時候發現還是超內存了。。。T_T。。。這麼好的方法還超內存。。。。後來花姐(博客:http://blog.csdn.net/lsh670660992)給我說,set用的內存只有map的一半,非常感謝拉!!!
哦哈哈哈哈,這個好!!馬上改為用set。。過啦!!!!!!!!!!
用map超內存的代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
int nu[3][510];
bool cmp(int a, int b)
{
return a < b;
}
int main()
{
map<int,int>st;
int x[3],smin,smax;
int i,t,n,tem,j;
int s;
int sum;
t = 0;
while(scanf("%d%d%d",&x[0],&x[1],&x[2])!=EOF)
{
st.clear();
t++;
for(i = 0; i < 3; i++)
{
for(j = 0; j < x[i]; j++)
{
scanf("%d",&nu[i][j]);
}
}
for(i = 0; i < x[0]; i++)
{
sum = nu[0][i];
for(j = 0; j < x[1]; j++)
{
st[sum+nu[1][j]] = 1;
}
}
printf("Case %d:\n",t);
scanf("%d",&n);
while(n--)
{
int p = 0;
scanf("%d",&s);
for(i = 0; i < x[2]; i++)
{
if(st[s-nu[2][i]] == 1)
{
p++;
break;
}
}
if(p)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
using namespace std;
int nu[3][510];
bool cmp(int a, int b)
{
return a < b;
}
int main()
{
set<int> st;
int x[3],smin,smax;
int i,t,n,tem,j;
int s;
int sum;
t = 0;
while(scanf("%d%d%d",&x[0],&x[1],&x[2])!=EOF)
{
st.clear();
t++;
for(i = 0; i < 3; i++)
{
for(j = 0; j < x[i]; j++)
{
scanf("%d",&nu[i][j]);
}
}
for(i = 0; i < x[0]; i++)
{
sum = nu[0][i];
for(j = 0; j < x[1]; j++)
{
st.insert(sum+nu[1][j]);
}
}
printf("Case %d:\n",t);
scanf("%d",&n);
while(n--)
{
int p = 0;
scanf("%d",&s);
for(i = 0; i < x[2]; i++)
{
if(st.count(s-nu[2][i]))
{
p++;
break;
}
}
if(p)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}