POJ 2785 4 Values whose Sum is 0(折半枚举)
给出四个长度为n的数列a,b,c,d,求从这四个数列中每个选取一个元素后的和为0的方法数。n<=4000,abs(val)<=2^28.
考虑直接暴力,复杂度O(n^4).显然超时。
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi acos(-1.0) # define eps 1e-3 # define MOD 1000000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=4005; //Code begin... int a[N], b[N], c[N], d[N]; VI vis; int main () { int n; LL ans=0; n=Scan(); FOR(i,1,n) a[i]=Scan(), b[i]=Scan(), c[i]=Scan(), d[i]=Scan(); FOR(i,1,n) FOR(j,1,n) vis.pb(-c[i]-d[j]); sort(vis.begin(),vis.end()); FOR(i,1,n) FOR(j,1,n) { int temp=a[i]+b[j]; ans+=upper_bound(vis.begin(),vis.end(),temp)-lower_bound(vis.begin(),vis.end(),temp); } printf("%lld\n",ans); return 0; }
枚举a,二分b+c+d.复杂度O(n+n^3*log(n^3)+n*log(n^3))~O(n^3*logn).
枚举a+b,二分b+c.复杂度O(n^2+n^2*log(n^2)+n^2*log(n^2))~O(n^2*logn).
枚举a+b+c,二分d.复杂度O(n^3+logn+n^3*logn)~O(n^3*logn).
另外此题map常数大过不了。