CCF-稀疏向量(100分)
阿新 • • 發佈:2020-08-05
由於從第四個測試點開始,n達到10^5,若用暴力列舉,即便加上找到答案就break,仍然超時,故不能採用o(n^2)的暴力列舉,這裡採用了雙指標演算法,只需將u,v序列各遍歷一次即可求出,時間複雜度為o(n),故不會超時
#include<iostream> #include<vector> using namespace std; typedef long long LL; typedef pair<int ,int >PII; LL res; int main(){ int n,a,b; cin>>n>>a>>b; vector<PII> u,v; while(a--){ int index,value; cin>>index>>value; u.push_back(make_pair(index,value)); } while (b--){ int index,value; cin>>index>>value; v.push_back(make_pair(index,value)); } for(int i=0,j=0;i<u.size()&&j<v.size();)//雙指標演算法 if (v[j].first<u[i].first)j++; else if (v[j].first==u[i].first){ res+=(LL)v[j].second*u[i].second; i++; j++; } else i++; cout<<res<<endl; return 0; }