【题解】codeforce1237 B. Balanced Tunnel⭐⭐【双指针】

codeforce1237 B. Balanced Tunnel⭐⭐

Consider a tunnel on a one-way road. During a particular day, n cars numbered from 1 to n entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.

A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.

Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.

Traffic regulations prohibit overtaking inside the tunnel. If car i overtakes any other car j inside the tunnel, car i must be fined. However, each car can be fined at most once.

Formally, let’s say that car i definitely overtook car j if car i entered the tunnel later than car j and exited the tunnel earlier than car j. Then, car i must be fined if and only if it definitely overtook at least one other car.

Find the number of cars that must be fined.

Input

The first line contains a single integer n (2≤n≤105), denoting the number of cars.

The second line contains n integers a1,a2,…,an (1≤ai≤n), denoting the ids of cars in order of entering the tunnel. All ai are pairwise distinct.

The third line contains n integers b1,b2,…,bn (1≤bi≤n), denoting the ids of cars in order of exiting the tunnel. All bi are pairwise distinct.

Output

Output the number of cars to be fined.

Examples

inputCopy
5
3 5 2 1 4
4 3 2 5 1
outputCopy
2
inputCopy
7
5 2 3 6 7 1 4
2 3 6 7 1 4 5
outputCopy
6
inputCopy
2
1 2
1 2
outputCopy
0




题意:

给出2个序列, 判断第二个序列不符合第一个序列中顺序的数有多少

题解:

双指针扫描一下, O(N)的就可写了


#include
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int INF = 1 << 30;
const int MAXN = 1e5+10;

int n, a[MAXN], b[MAXN];
bool used[MAXN];
int main() {
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i = 1; i <= n; ++i)
        cin >> a[i];
    for(int i = 1; i <= n; ++i)
        cin >> b[i];
    int ans = 0;
    for(int i = 1, j = 1; i <= n && j <= n;){
        if(used[a[i]]){
            ++i;
            continue;
        }if(a[i] == b[j])
            ++j, ++i;
        else
            used[b[j]] = true, ++ans, ++j;

    }
    cout << ans << endl;

    return 0;
}

你可能感兴趣的:(枚举,思维)