Description
Jaap, Jan, and Thijs are on a trip to the desert after having attended the ACM ICPC World Finals 2015 in Morocco. The trip included a camel ride, and after returning from the ride, their guide invited them to a big camel race in the evening. The camels they rode will also participate and it is customary to bet on the results of the race. One of the most interesting bets involves guessing the complete order in which the camels will finish the race. This bet offers the biggest return on your money, since it is also the one that is the hardest to get right.
Jaap, Jan, and Thijs have already placed their bets, but the race will
not start until an hour from now, so they are getting bored. They
started wondering how many pairs of camels they have put in the same
order. If camel c is before camel d on Jaap’s, Jan’s and Thijs’ bet, it
means that all three of them put c and d in the same order. Can you help
them to calculate the number of pairs of camels for which this
happened?
Input
The input consists of:
- one line with an integer n (2 ≤ n ≤ 200 000), the number of camels;
- one line with n integers a1,...,an (1≤ai≤n for all i), Jaap’s bet. Here a1 is the camel in the first position of Jaap’s bet, a2 is the camel in the second position, and so on;
- one line with Jan’s bet, in the same format as Jaap’s bet;
- one line with Thijs’ bet, in the same format as Jaap’s bet.
The camels are numbered 1, … , n. Each camel appears exactly once in each bet.
Output
Output the number of pairs of camels that appear in the same order in all 3 bets.
Sample Input
Sample input 1
3
3 2 1
1 2 3
1 2 3
Sample input 2
4
2 3 1 4
2 1 4 3
2 4 3 1
Sample Output
Sample output 1
0
Sample output 2
3
固定一个顺序,查找另一个顺序,贴代码主要是学习一下高效输入。
//(总对数减去不同的)/2; #include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <cmath> #include <vector> #include <algorithm> using namespace std; typedef long long ll; #define lowbit(x) x&(-x) #define max(x,y) (x>y?x:y) #define min(x,y) (x<y?x:y) #define mem(a) (memset(a,0,sizeof(a))) int a[4][200006],pos[200006],vis[200006],n; inline int iread(){ int f = 1, x = 0; char ch = getchar(); for(; ch < ‘0‘ || ch > ‘9‘; ch=getchar())f = ch==‘-‘?-1:1; for(; ch <= ‘9‘ && ch >= ‘0‘; ch=getchar())x = x*10+ch-‘0‘; return f*x; } inline void add(int x) { for(int i=x;i<=n;i+=lowbit(i)) { vis[i]+=1; } } inline ll query(int x) { ll ans=0; for(int i=x;i;i-=lowbit(i)) { ans+=vis[i]; } return ans; } int main() { while(scanf("%d",&n)!=EOF) { ll ans=0; for(int i=0;i<3;i++) { for(int j=1;j<=n;j++) { a[i][j]=iread(); //scanf("%d",&a[i][j]); } } for(int i=0;i<3;i++) { memset(vis,0,sizeof(vis)); for(int j=1;j<=n;j++) { pos[a[i][j]]=j; } for(int j=n;j;j--) { ans+=query(pos[a[(i+1)%3][j]]); add(pos[a[(i+1)%3][j]]); } } printf("%lld\n",(1ll*n*(n-1)-ans)>>1); } return 0; }