Why Did the Cow Cross the Road III(樹狀數組)
Why Did the Cow Cross the Road III
時間限制: 1 Sec 內存限制: 128 MB提交: 65 解決: 28
[提交][狀態][討論版]
題目描述
The layout of Farmer John‘s farm is quite peculiar, with a large circular road running around the perimeter of the main field on which his cows graze during the day. Every morning, the cows cross this road on their way towards the field, and every evening they all cross again as they leave the field and return to the barn.
Looking at his map of crossing points, Farmer John is curious how many times various pairs of cows might cross paths during the day. He calls a pair of cows (a,b) a "crossing" pair if cow a‘s path from entry to exit must cross cow b‘s path from entry to exit. Please help Farmer John count the total number of crossing pairs.
輸入
The first line of input contains N (1≤N≤50,000), and the next 2N lines describe the cow IDs for the sequence of entry and exit points around the field.輸出
Please print the total number of crossing pairs.樣例輸入
4
3
2
4
4
1
3
2
1
樣例輸出
3
【題意】在一個圓上,順時針 給出一些數字,每個數字出現兩遍,然後數字相同的連邊,問多少對邊相交。
【分析】我們可以發現按照題目給出的數據順序,如果兩個數的連線相交,那麽他倆在一維中的連線一相交,也就是如果某個數兩次出現
的位置中間有多少個數 出現了一次,那麽就有多少條線與他相交,那我們直接對於每個數統計兩個位置之間的出現一次的數就行了。
對於這種數據量較大無法N方解決的統計問題,樹狀數組一般都可以。對於這個題,從左到右掃,當第一次掃到這個數時,從這個位置
向上lowbit依次+1,當第二次掃到這個數的時候,統計第一次出現的位置到當前位置的sum值,然後從第一次出現的位置向上lowbit
依次-1,表示刪除此邊。
#include <bits/stdc++.h> #define inf 0x3f3f3f3f #define met(a,b) memset(a,b,sizeof a) #define pb push_back #define mp make_pair #define inf 0x3f3f3f3f using namespace std; typedef long long ll; const int N = 1e5+50; const int mod = 1e9+7; const double pi= acos(-1.0); typedef pair<int,int>pii; int n,ans; int a[N],sum[N],vis[N]; void upd(int x,int add){ for(int i=x;i<=2*n;i+=i&(-i)){ sum[i]+=add; } } int qry(int x){ int ret=0; for(int i=x;i>=1;i-=i&(-i)){ ret+=sum[i]; } return ret; } int main(){ scanf("%d",&n); for(int i=1;i<=2*n;i++){ scanf("%d",&a[i]); } for(int i=1;i<=2*n;i++){ if(!vis[a[i]]){ upd(i,1); vis[a[i]]=i; } else { int s=qry(i-1)-qry(vis[a[i]]); //printf("i:%d ai:%d l:%d r:%d\n",i,a[i],qry(vis[a[i]]),qry(i-1)); ans+=s; upd(vis[a[i]],-1); } } printf("%d\n",ans); return 0; }
Why Did the Cow Cross the Road III(樹狀數組)