1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; #define int long long #define N 150006
int n,k,q; vector<int> vec[N],pre[N]; bool visit[N]; cc_hash_table<int,int>cc; int HASH(int x,int y){ return x*1000000007+y; } signed main(){ scanf("%lld %lld %lld",&n,&k,&q); memset(visit, 0, sizeof(visit)); while(k--){ int c,p;scanf("%lld %lld",&c,&p); vec[p].push_back(c); } while(q--){ int x,y;scanf("%lld %lld",&x,&y); if(vec[x].size()>vec[y].size())swap(x, y); if(cc.find(HASH(x,y))!=cc.end()){ printf("%lld\n",cc.find(HASH(x,y))->second); continue; } else if(cc.find(HASH(y,x))!=cc.end()){ printf("%lld\n",cc.find(HASH(y,x))->second); continue; } int len = vec[y].size(); if(!visit[y]){ sort(vec[y].begin(),vec[y].end()); pre[y].resize(len+6); for(int i=0;i<=len;i++)pre[y][i+1] = pre[y][i]+vec[y][i]; visit[y] = 1; } int ans = 0; for(int j:vec[x]){ int pos = lower_bound(vec[y].begin(), vec[y].end(),j)-vec[y].begin(); pos--; if(pos<0)ans+=(len*j); else ans += (pre[y][pos+1]+j*(len-pos-1)); } printf("%lld\n",ans); cc.insert(make_pair(HASH(x,y),ans)); cc.insert(make_pair(HASH(y,x),ans)); } }
|