CCF-稀疏向量(100分)


由於從第四個測試點開始,n達到105,若用暴力枚舉,即便加上找到答案就break,仍然超時,故不能采用o(n2)的暴力枚舉,這里采用了雙指針算法,只需將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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM