import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] k = new int[n];
        boolean[][] a = new boolean[n][m + 1];
        for (int i = 0; i < n; i++) {
            k[i] = sc.nextInt();
            for (int j = 0; j < k[i]; j++) {
                int x = sc.nextInt();
                a[i][x] = true;
            }
        }
        // System.out.println(Arrays.deepToString(a));
        int ans = 0;
        boolean[] ok = new boolean[m + 1];
        Arrays.fill(ok, true);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= m; j++) {
                // System.out.println("i = " + i);
                // System.out.println("j = " + j);
                // System.out.println(a[i][j]);
                if (!a[i][j]) {
                    ok[j] = false;
                }
            }
        }
        for (int i = 0; i <= m; i++) {
            if (ok[i]) {
                ans++;
            }
        }
        // System.out.println(Arrays.toString(ok));
        System.out.println(ans);
    }
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] str = in.readLine().split(" ");
    int n = Integer.parseInt(str[0]);
    int m = Integer.parseInt(str[1]);
    int a[] = new int[m];
    for(int i=0; i<n; i++) {
      str = in.readLine().split(" ");
      int k = Integer.parseInt(str[0]);
      for(int j=1; j<=k; j++) {
        int t = Integer.parseInt(str[j]);
        System.out.println(t);
        a[t-1]++;
      }
    }

    int count = 0;
    for(int i=0; i<m; i++) {
      if(a[i] == n)
        count++;
    }
    System.out.println(count);
  }
}


import java.util.*;
public class Main {
    public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		int c = sc.nextInt();
        int a[] = new int[n-1];
        int b[][] = new int[n][30];
        int ans[] = new int[c];

        for(int i=0; i<c; i++){
            ans[i] = sc.nextInt();
        }

        for(int i=0; i<n-1; i++){
            a[i] = sc.nextInt();
            for(int j=0; j<a[i]; j++){
                b[i][j] = sc.nextInt();
            }
        }

        for(int i=0; i<c; i++){
            for(int j=0; j<n-1; j++){
                for(int k=0; k<a[j]; k++){
                    if(ans[i] != b[j][k]){
                        ans[i] = 0;
                    }
                }
            }
        }

        int flg = 0;

        for(int i=0; i<c; i++){
            if(ans[i]!=0){
                System.out.println(ans[c]);
                flg = 1;
            }
        }

        if(flg == 0){
            System.out.println(0);
        }
    }
}


import java.util.*;
import java.util.ArrayList;

public class Main{

  public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int M = sc.nextInt();

    if(N == 1){
      int count1 = 0;
      int K1 = sc.nextInt();
      for(int i = 0; i < K1 ; i++){
        int love = sc.nextInt();
        if(love <= M){
          count1++;
        }
      }

      System.out.println(count1);

    }else{

    ArrayList<Integer> love = new ArrayList<Integer>();
    for(int i = 0; i < N ; i++){
      int K = sc.nextInt();
      int[] list = new int[K];
       for(int j = 0; j < K ; j++){
         list[j] = sc.nextInt();
         love.add(list[j]);
       }
    }

    ArrayList<Integer> countAll = new ArrayList<Integer>();
    int count = 0;
    for(int i = 0; i < love.size() ; i++){
      int jd = love.get(i);
      for(int j = 0; j  < M ; j++){
        if(jd == j+1){
          count++;
        }
      }
      countAll.add(count);
      count = 0;
    }

    int lastCount = 0;
    for(int i = 0; i < M ; i++){
      if(countAll.get(i) == M){
        lastCount++;
      }
    }
    System.out.println(lastCount);
    }
  }
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <queue>
#include <tuple>

#define INF 100000000

using namespace std;

int main()
{
    int n, m;
    cin >> n >> m;
    int a[m] = {0};
    for (int i = 0; i < n; i++)
    {
        int k, tmp;
        cin >> k;
        for (int j = 0; j < k; j++)
        {
            cin >> tmp;
            a[tmp - 1]++;
        }
    }
    int ans = 0;
    for (int i = 0; i < m; i++)
    {
        if (a[i] == n)
        {
            ans++;
        }
    }
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
// type alias
typedef long long LL;
typedef pair<int,int> II;
typedef tuple<int,int,int> III;
typedef vector<int> VI;
typedef vector<string> VS;
typedef unordered_map<int,int> MAPII;
typedef unordered_set<int> SETI;
template<class T> using VV=vector<vector<T>>;
// minmax
template<class T> inline T SMIN(T& a, const T b) { return a=(a>b)?b:a; }
template<class T> inline T SMAX(T& a, const T b) { return a=(a<b)?b:a; }
// repetition
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n)  for(int i=0;i<=(n);++i)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  for(int i=0;i<(n);++i)
#define FORR(x,arr) for(auto& x:arr)
#define SZ(a) int((a).size())
// collection
#define ALL(c) (c).begin(),(c).end()
// DP
#define MINUS(dp) memset(dp, -1, sizeof(dp))
#define ZERO(dp) memset(dp, 0, sizeof(dp))
// stdout
#define println(args...) fprintf(stdout, ##args),putchar('\n');
// debug cerr
template<class Iter> void __kumaerrc(Iter begin, Iter end) { for(; begin!=end; ++begin) { cerr<<*begin<<','; } cerr<<endl; }
void __kumaerr(istream_iterator<string> it) { (void)it; cerr<<endl; }
template<typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr<<*it<<"="<<a<<", ",__kumaerr(++it, args...); }
template<typename S, typename T> std::ostream& operator<<(std::ostream& _os, const std::pair<S,T>& _p) { return _os<<"{"<<_p.first<<','<<_p.second<<"}"; }
#define __KUMATRACE__ true
#ifdef __KUMATRACE__
#define dump(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); __kumaerr(_it, args); }
#define dumpc(ar) { cerr<<#ar<<": "; FORR(x,(ar)) { cerr << x << ','; } cerr << endl; }
#define dumpC(beg,end) { cerr<<"~"<<#end<<": "; __kumaerrc(beg,end); }
#else
#define dump(args...)
#define dumpc(ar)
#define dumpC(beg,end)
#endif

// $ cp-batch FoodsLovedByEveryone | diff FoodsLovedByEveryone.out -
// $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address FoodsLovedByEveryone.cpp && ./a.out

/*

 2/28/2019

 15:33-

 */

const int MAX_N=1e6+1;
LL A[MAX_N];
int N,M;

void solve() {
  int res=0;
  REP(i,M) res+=(A[i]==N);
  cout<<res<<endl;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout<<setprecision(12)<<fixed;

  cin>>N>>M;
  REP(i,N) {
    int K; cin>>K;
    REP(i,K) {
      int a; cin>>a;
      A[--a]++;
    }
  }
  solve();

  return 0;
}


#include <iostream>
#include <math.h>
#include <string>
#include <algorithm>
#include <ctype.h>
#include <vector>
using namespace std;

#define ll long long int
#define rep(i, a, n) for (int i = a; i < n; i++)
#define INF 1e9
#define LINF 1e17
#define MOD (int)(1e9 + 7)
#define pi 3.141592653589
#define pii pair<int, int>
#define vi vector<int>
#define ALL(a) (a).begin(), (a).end()
#define sort_v(a) sort(a.begin(), a.end())

void print(int a)
{
    if (a != 0)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main()
{
    int n, m;
    cin >> n >> m;

    bool like[31];
    rep(i, 0, m) like[i] = true;

    int a[31][31] = {}, k[31] = {};
    rep(i, 0, n)
    {
        cin >> k[i];
        rep(j, 0, k[i])
        {
            cin >> a[i][j];
        }
    }

    int ans = 0;
    rep(l, 1, m + 1)
    {
        //cout << "l=" << l << endl;
        rep(i, 0, n)
        {
            bool f = true;
            rep(j, 0, k[i])
            {
                //cout << a[i][j] << " ";
                if (a[i][j] == l)
                {
                    if (i == n - 1)
                    {
                        ans++;
                        //f = false;
                    }
                    break;
                }
                if (j == k[i] - 1)
                    f = false;
            }
            //cout << endl;
            if (!f)
                break;
        }
    }
    cout << ans << endl;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <string>
#include <set>
#include <math.h>
#include <map>
#include <stack>
using namespace std;
static const int INF = 1e9+7;
// 型定義
typedef long long ll;
typedef pair<ll, ll> P;

#define rep(i, n) for (int i = 0; i < n; i++)
#define repr(i, a, b) for (int i =a; i < b; i++)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define PI 3.14159265359

int main(){

    int n, m; cin >> n >> m;
    int kind[50] = {};

    rep(i,n){
        int k; cin >> k;
        rep(i, k){
            int tmp; cin >> tmp;
            kind[tmp]++;
        }
    }

    int ans = 0;
    rep(i,m){
        if(kind[i] == n) ans++;
    }

    cout << ans << endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define rev(i, n) for(int i = (int)(n - 1); i >= 0; i--)
#define rev1(i, n) for(int i = (int)(n); i > 0; i--)
#define pb push_back
#define ts to_string
#define all(v) (v).begin(), (v).end()
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vs vector <string>
#define vvs vector <vector<string>>
#define pq  priority_queue<int>
using ll = long long;
/* ----------------よく使う数字や配列----------------- */
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };
const int INF = 2000000000;
const int MINF=-2000000000;
constexpr ll mod = 1e9 + 7;
constexpr long double pi = 3.141592653589793238462643383279;
/* ----------------------end----------------------- */
/* --------------------ライブラリ-------------------- */
ll fact(int i) {       //階乗
    if (i == 0) return 1;
    return (fact(i - 1)) * i % mod;
}
ll gcd(ll a, ll b) {        //最大公約数
    if (b == 0) return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) {      //最小公倍数
    return a * b / gcd(a, b);
}
bool isprime(ll a)//素数判定、primeならtrue,違うならfalse
{
    if (a < 2) return false;
    else if (a == 2) return true;
    else if (a % 2 == 0) return false;
    double m = sqrt(a);
    for (int i = 3; i <= m; i += 2)
    {
        if (a % i == 0)
        {
            return false;
        }
    }
    // 素数である
    return true;
}
ll ketasum(ll n) {    //各桁の和
    ll sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

/* ----------------------end----------------------- */
signed main() {
    int N, M; cin >> N >> M;
    vvi A(N);
    vi K;
    rep(i, N) {
        int k; cin >> k;
        K.push_back(k);
        rep(i, k) {
            int a; cin >> a;
            A[i].push_back(a);
        }
    }
    vi like(M);
    rep(i, N) {
        for (int j = 0; j < K[i]; j++) {
            like[A[i][j]-1]++;
        }
    }
    int cnt = 0;
    rep(i, M) {
        if (like[i] == N)cnt++;
    }
    cout << cnt << endl;
}


#pragma region header
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <math.h>
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define rev(i, n) for(int i = (int)(n - 1); i >= 0; i--)
#define rev1(i, n) for(int i = (int)(n); i > 0; i--)
#define pb push_back
#define ts to_string
#define all(v) (v).begin(), (v).end()
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vs vector <string>
#define vvs vector <vector<string>>
#define pq  priority_queue<int>
using ll = long long;
/* ----------------よく使う数字や配列----------------- */
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };
const int INF = 2000000000;
const int MINF=-2000000000;
constexpr ll mod = 1e9 + 7;
constexpr long double pi = 3.141592653589793238462643383279;
/* ----------------------end----------------------- */
/* --------------------ライブラリ-------------------- */
ll fact(int i) {       //階乗
    if (i == 0) return 1;
    return (fact(i - 1)) * i % mod;
}
ll gcd(ll a, ll b) {        //最大公約数
    if (b == 0) return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) {      //最小公倍数
    return a * b / gcd(a, b);
}
bool isprime(ll a)//素数判定、primeならtrue,違うならfalse
{
    if (a < 2) return false;
    else if (a == 2) return true;
    else if (a % 2 == 0) return false;
    double m = sqrt(a);
    for (int i = 3; i <= m; i += 2)
    {
        if (a % i == 0)
        {
            return false;
        }
    }
    // 素数である
    return true;
}
ll ketasum(ll n) {    //各桁の和
    ll sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
ll kind(vi SYURUI) {//vector<int>型の配列の要素の種類数
    int size = SYURUI.size();
    sort(all(SYURUI));
    int cnt = 1;
    rep(i, size-1) {
        if (SYURUI[i] != SYURUI[i + 1])cnt++;
    }
    return cnt;
}
/* ----------------------end----------------------- */
#pragma endregion

signed main() {
    int N, M; cin >> N >> M;
    vvi A(N);
    vi K;
    rep(i, N) {
        int k; cin >> k;
        K.push_back(k);
        rep(i, k) {
            int a; cin >> a;
            A[i].push_back(a);
        }
    }
    vi like(M);
    rep(i, N) {
        for (int j = 0; j < K[i]; j++) {
            like[A[i][j]-1]++;
        }
    }
    int cnt = 0;
    rep(i, M) {
        if (like[i] == N)cnt++;
    }
    cout << cnt << endl;
}


#include<stdio.h>

int main(void)
{
  int n,m;
  scanf("%d%d",&n,&m);

  int i,j,k[n],a[n][m];
  int judge[m];
  for(i=0;i<m;i++)
    judge[i] = 0;
  for(i=0;i<n;i++){
    scanf("%d",&k[i]);
    for(j=0;j<k[i];j++){
      scanf("%d",&a[i][j]);
      judge[a[i][j]-1]++;
    }
  }

  int ans=0;
  for(i=0;i<m;i++)
    if(judge[i]==n){
      ans++;
    }

  printf("%d\n",ans);
  return 0;
}


#include <stdio.h>
int main(void)
{

	int n,m,A=0,k[30]={0},x,y;

	scanf("%d%d",&n,&m);
	    for(int i=0;i<n;i++){
        scanf("%d",&x);
       	    for(int j=0;j<x;j++){
              scanf("%d",&y);
                 k[y-1]++;
        }

 }
    for(int i=0;i<m;i++){
        if(k[i]==n) A++;}

    printf("%d",A);

}


#include<stdio.h>
int main(){
  int n, m;
  scanf("%d %d",&n,&m);

  int cnt[30] = {};
  int k, a;
  for(int i = 0; i < n; i++){
    scanf("%d",&k);
    for(int j = 0; j < k; j++){
      scanf("%d",&a);
      cnt[a-1]++;
    }
  }

  int ans = 0;
  for(int i = 0; i < m; i++){
    if(cnt[i] == n){
      ans++;
    }
  }
  printf("%d",ans);
}


#include "stdio.h"

int main(){
    int N,M,K,i,j,F[31][31],t;
    scanf("%d%d",&N,&M);
    for(i=0;i<N;i++){
        scanf("%d",&K);
        for(j=0;j<K;j++){
            scanf("%d",&t);
            F[i][t]=1;
        }
    }
    t=0;
    for(i=1;i<=M;i++){
        int f=1;
        for(j=0;j<N;j++){
            if(F[j][i]!=1){
                f=0;
                break;
            }
        }
        if(f==1){
            t++;
        }
    }
    printf("%d",t);
    return 0;
}


#include "stdio.h"

int main(){
    int N,M,K,i,j,F[31][31],t;
    scanf("%d%d",&N,&M);
    for(i=0;i<N;i++){
        scanf("%d",&K);
        for(j=0;j<K;j++){
            scanf("%d",&t);
            F[i][t]=1;
        }
    }
    t=0;
    for(i=1;i<=M;i++){
        int f=1;
        for(j=0;j<N;j++){
            if(F[j][i]){
                f=0;
                break;
            }
        }
        if(f){
            t++;
        }
    }
    printf("%d",t);
    return 0;
}


#include <stdio.h>

int main(void)
{
        int n,m,k,i,j,s;
        scanf("%d%d",&n,&m);

        int a[n][m],c[m];

        for(i=0;i<m;i++)
                c[i]=0;

        for(i=0;i<n;i++){
                scanf("%d",&k);
                for(j=0;j<k;j++){
                        scanf("%d",a[i][j]);
                        c[a[i][j]]++;
                }
        }

        s=0;
        for(i=0;i<m;i++)
                if(c[i]==m) s++;

        printf("%d\n",s);
        return 0;
}


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
line = lines.shift().split(' ')
n = line[0] * 1
m = line[1] * 1
arr = []
for (i=0; i<m; i++) {
    arr[i] = 0
}

for (i=0; i<n; i++) {
    line = lines[i].split(' ')
    k = line[0]
    for (j=1; j<=k; j++) {
        arr[line[j]-1] += 1
    }
}

cnt = 0;
for (i=0; i<m; i++) {
    if (arr[i] == n) {
        cnt++
    }
}
console.log(cnt)


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.split("\n")
  tmp0 = input[0].split(" ")

  N = Number(tmp0[0])
  M = Number(tmp0[1])

  var ansArr=[];
  for(var i=0; i < M; i++){
    ansArr.push(0)
  }

  for(var i=1; i <= N; i++)
  {
    var tmp1 = input[i].split(" ")
    for(var j = 1; j < tmp1.length; j++){
      ansArr[tmp1[j]-1]++
    }
  }

  var ans=0
  for(var i=0; i < ansArr.length;i++)
  {
    if(ansArr[i] === N){
      ans++
    }
  }
  console.log(ans)

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// Main("3 4\n2 1 3\n3 1 2 3\n2 3 2")


'use strict'

function main(input) {
  input = input.split('\n').map(v => v.split(' ').map(v => ~~v))
  const n = input[0][0]
  const m = input[0][1]
  const ans = input.slice(1, -1)
  const counts = Array.apply(null, { length: m + 1 }).fill(0)
  for (let i = 0; i < n; i++) {
    for (let j = 1; j <= ans[i][0]; j++) {
      counts[ans[i][j]] += 1
    }
  }

  const f = counts.filter(v => {
    return v >= n
  })

  console.log(f.length)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))


function main(input) {
  const args = input.split('\n');
  const a = args[0].split(' ').map(n => parseInt(n, 10));
  const N = a[0];
  const M = a[1];

  let list = {};
  let ans = 0;

  //リスト初期化
  for (let i = 1; i <= M; i++) {
    list[i] = 0;
  }

  //各人の好きな食べ物ループ
  for (let i = 1; i <= N; i++) {
    ary = args[i].split(' ').map(n => parseInt(n, 10));
    for (let j = 1; j <= ary[0]; j++) {
      key = ary[i];
      list[key]++;
    }
  }

  //みんなが好きならプラスする
  for (key in list) {
    if (list[key] === N) { ans++; }
  }

  console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'

const main = (INPUT) => {
  const input = INPUT.split('\n')
  const [N, M] = input[0].split(' ')
  const K = input.slice(1)
  let ans = Array.from(new Array(Number(M))).map((v, i) => i + 1)
  for (let i = 0; i < K.length; i++) {
    const tmp = K[i].split(' ').slice(1).map(n => Number(n))
    for (let j = 0; j < ans.length; j++) {
      if (!tmp.includes(ans[j])) {
        ans[j] = null
      }
    }
  }
  console.log(ans.filter(v => v != null).length)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


n,m=map(int,input().split())
count=0
ans=0
d=[0]*m
for i in range(n):
  a=list(map(int,input().split()))
  a.pop(0)
  for j in a:
    d[j-1]+=1
print(d.count(n))


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
	"strconv"
)

const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
)

func main() {
	N := getInt()
	getInt()

	answer := make(map[int]int)
	for i := 0; i < N; i++ {
		k := getInt()
		for j := 0; j < k; j++ {
			a := getInt()
			answer[a]++
		}
	}

	cnt := 0
	for _, ans := range answer {
		if ans == N {
			cnt++
		}
	}
	fmt.Println(cnt)
}

type Graph struct {
	n     int
	edges [][]int
}

func NewGraph(n int) *Graph {
	g := &Graph{
		n:     n,
		edges: make([][]int, n),
	}
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.edges[v] = append(g.edges[v], u)
	g.edges[u] = append(g.edges[u], v)
}

func dfs(c int, edges [][]int, visited map[int]struct{}) {
	visited[c] = struct{}{}

	for _, v := range edges[c] {
		_, flag := visited[v]
		if flag {
			continue
		}
		dfs(v, edges, visited)
	}
}

func bfs(c int, graph *Graph) {
	next := make([]int, 0)
	next = append(next, c)
	visited := make(map[int]struct{})

	for ; len(next) != 0; {
		u := next[0]
		next = next[1:]
		visited[u] = struct{}{}

		for _, v := range graph.edges[u] {
			_, flag := visited[v]
			if flag {
				continue
			}

			// なにか処理

			next = append(next, v)
		}
	}
}

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getIntArray(n int) []int {
	array := make([]int, n)
	for i := 0; i < n; i++ {
		array[i] = getInt()
	}
	return array
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray)-1])
}

func calcMod(x int) int {
	return x % mod
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func isPrime(n int) bool {
	if n < 2 {
		return false
	} else if n == 2 {
		return true
	} else if n % 2 == 0 {
		return false
	}

	sqrtN := int(math.Sqrt(float64(n)))
	for i := 3; i <= sqrtN; i += 2 {
		if n % i == 0 {
			return false
		}
	}

	return true
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

func makeRange(min, max int) []int {
	a := make([]int, max-min+1)
	for i := range a {
		a[i] = min + i
	}
	return a
}

func powerset2(nums []int) [][]int {
	length := int(math.Pow(2, float64(len(nums))))
	result := make([][]int, length)

	index := 0
	result[index] = []int{}
	index++

	for _, n := range nums {
		max := index
		for i := 0; i < max; i++ {
			result[index] = copyAndAppend(result[i], n)
			index++
		}
	}

	return result
}

func copyAndAppend(nums []int, n int) []int {
	dst := make([]int, len(nums)+1)
	copy(dst, nums)
	dst[len(nums)] = n
	return dst
}

func calcGcd(x, y int) int {
	if y == 0 {
		return x
	} else if x >= y {
		return calcGcd(y, x % y)
	} else {
		return calcGcd(x, y % x)
	}
}

func getDivisor(n int) []int {
	var divisor []int
	divisor = append(divisor, 1)
	if n != 1 {
		divisor = append(divisor, n)
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n % i == 0 {
			divisor = append(divisor, i)
			divisor = append(divisor, n/i)
		}
	}
	return divisor
}

type intHeap []int

func (h intHeap) Len() int {
	return len(h)
}

func (h intHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h intHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func initHeap() *intHeap {
	ih := &intHeap{}
	heap.Init(ih)
	return ih
}

func (h *intHeap) pushHeap(n int) {
	heap.Push(h, n)
}

func (h *intHeap) popHeap() int {
	return heap.Pop(h).(int)
}

func factMod(n int) int {
	value := 1
	for ; n > 1; n-- {
		value = calcMod(value * n)
	}
	return value
}

func combinationMod(n, k int) int {
	factN := factMod(n)
	factK := factMod(k)
	factNK := factMod(n - k)
	factKR := powMod(factK, mod - 2)
	factNKR := powMod(factNK, mod - 2)
	return calcMod(factN * calcMod(factKR * factNKR))
}


package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

func main() {
	n, m := readInt(), readInt()
	cnt := map[int]int{}
	for i := 0; i < m; i++ {
		cnt[i+1] = 0
	}

	for i := 0; i < n; i++ {
		k := readInt()
		for j := 0; j < k; j++ {
			cnt[readInt()]++
		}
	}

	ans := 0
	for _, v := range cnt {
		if v == n {
			ans++
		}
	}

	fmt.Println(ans)
}

// sort ------------------------------------------------------------

type xxx struct {
	x int
}

type sortArray []xxx

func (s sortArray) Len() int           { return len(s) }
func (s sortArray) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s sortArray) Less(i, j int) bool { return s[i].x < s[j].x }

// -----------------------------------------------------------------

var (
	readString func() string
	readBytes  func() []byte
)

func init() {
	readString, readBytes = newReadString(os.Stdin)
}

func newReadString(ior io.Reader) (func() string, func() []byte) {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)

	f1 := func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
	f2 := func() []byte {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Bytes()
	}
	return f1, f2
}

func readInt() int {
	return int(readInt64())
}

func readInt64() int64 {
	i, err := strconv.ParseInt(readString(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(readString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func sum(a []int) int {
	var ret int
	for i := range a {
		ret += a[i]
	}
	return ret
}

func sumFloat64(a []float64) float64 {
	var ret float64
	for i := range a {
		ret += a[i]
	}
	return ret
}

func gcd(m, n int) int {
	for m%n != 0 {
		m, n = n, m%n
	}
	return n
}

func lcm(m, n int) int {
	return m / gcd(m, n) * n
}


package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

func input() string {
	sc.Scan()
	return sc.Text()
}

func main() {
	n, err := strconv.Atoi(input())
	if err != nil {
		log.Fatalln(err)
	}
	m, err := strconv.Atoi(input())
	if err != nil {
		log.Fatalln(err)
	}

	if n == 1 {
		k, err := strconv.Atoi(input())
		if err != nil {
			log.Fatalln(err)
		}
		fmt.Println(k)
		return
	}

	list := make(map[int]int)

	for i := 1; i <= m; i++ {
		list[i] = 0
	}

	for i := 0; i < n; i++ {
		k, err := strconv.Atoi(input())
		if err != nil {
			log.Fatalln(err)
		}
		for j := 0; j < k; j++ {
			a, err := strconv.Atoi(input())
			if err != nil {
				log.Fatalln(err)
			}
			list[a] += 1
		}
	}

	count := 0
	for _, v := range list {
		if v == n {
			count++
		}
	}

	fmt.Println(count)
}


package main

import "fmt"

func main() {
	var n, m int
	var previous []int

	fmt.Scanf("%d %d", &n, &m)
	for tmp := 0; tmp < m; tmp++ {
		previous = append(previous, tmp)
	}

	for i := 0; i < n; i++ {
		var now []int
		var k int
		fmt.Scanf("%d", &k)
		for j := 0; j < k; j++ {
			var a int
			fmt.Scanf("%d", &a)
			now = append(now, a)
		}
		previous = Uniform(previous, now)
	}
	fmt.Println(len(previous))
}

func In(a int, list []int) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}
func Uniform(previous, now []int) []int {
	var res []int
	for _, i := range now {
		if In(i, previous) {
			res = append(res, i)
		}
	}
	return res
}


package main

import (
  "fmt"
)

func main() {
  var n, m int
  fmt.Scan(&n, &m)
  res := 1 << uint(m) - 1
  for i := 0; i < n; i++ {
    var k int
    fmt.Scan(&k)
    like := 0
    for j := 0; j < k; j++ {
      var a uint
      fmt.Scan(&a); a--
      like |= 1 << a
    }
    res &= like
  }
  cnt := 0
  for i := uint(0); i < m; i++ {
    if res >> i & 1 == 1 {cnt++}
  }
  fmt.Println(cnt)

}


package main

import (
  "fmt"
)

func main() {
  var n, m int
  fmt.Scan(&n, &m)
  res := 1 << uint(m) - 1
  for i := 0; i < n; i++ {
    var k int
    fmt.Scan(&k)
    like := 0
    for j := 0; j < k; j++ {
      var a uint
      fmt.Scan(&a); a--
      like |= 1 << a
    }
    res &= like
  }
  cnt := 0
  for i := 0; i < m; i++ {
    if res >> i & 1 == 1 {cnt++}
  }
  fmt.Println(cnt)

}


nm = gets.chomp.split
n = nm[0].to_i
m = nm[1].to_i

foods = Array.new(m+1, 0)

n.times do
    input = gets.chomp.split
    k = input[0].to_i
    k.times do |i|
        a = input[i+1].to_i
        foods[a] += 1
    end
end

puts foods.count(n)


# frozen_string_literal: true

n, _m = gets.split.map(&:to_i)
h = Hash.new(0)
n.times do
  gets.split.map(&:to_i)[1..-1].each { |i| h[i] += 1 }
end

puts h.values.count { |i| i == n }


n,m = gets.split.map(&:to_i)

ans = [0]*(m+1)
n.times do |i|
  a = gets.split.map(&:to_i)
  k = a.shift
  a.each do |j|
    ans[j] += 1
  end
end

puts ans.count(n)


N,M = gets.chomp.split.map(&:to_i)
ary = (1..m).to_a

N.times do |i|
  buf = gets.chomp.split.map(&:to_i)
  ary = ary & buf[1..-1]
end

puts ary.length


n,m = gets.split.map(&:to_i)

a = gets.split.map(&:to_i)
t = a.slice(0,a[0])

(n-1).times do |i|
    a = gets.split.map(&:to_i)
    a = a.slice(0,a[0])
    t = t & a
end

# p t
p t.size


n, m = gets.split.map(&:to_i)
ans = []
n.times do
  ans.concat(gets.split.map(&:to_i)[1..-1])
end

(1..m).each do |i|
  if ans.count(i) == n
    count+=1
  end
end
puts count


use std::io;
use std::str::FromStr;

fn input_tuple() -> (u64, u64) {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    let vec: Vec<u64> = line.split_whitespace().map(|s| s.parse().unwrap()).collect();
    (vec[0], vec[1])
}

fn input_vec() -> Vec<u64> {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    line.split_whitespace().map(|s| s.parse().unwrap()).collect()
}

fn main() {
    let (n, m) = input_tuple();
    let mut flag = vec![0; m as usize];
    for _ in 0..n {
        let v = input_vec();
        let k = v[0];
        for i in 1..(k+1) {
            flag[v[i as usize] as usize - 1] += 1;
        }
    }
    // println!("{:?}", flag);
    let mut count = 0;
    for f in flag {
        if f == n {
            count += 1;
        }
    }
    println!("{}", count);
}


use std::io::*;
use std::str::FromStr;

/*
The read function reads a string according to each one.
*/
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

//main function
fn main() {
    let n: usize = read();
    let m: usize = read();
    let mut a: Vec<i32> = Vec::with_capacity(m+1);
    let mut count: i32 = 0;
    unsafe{
	a.set_len(m+1);
    }
    for i in 0..m+1{
	a[i as usize] = 0;
    }
    for _i in 0..n{
	let k: usize = read();
	for _j in 0..k{
	    let b: usize = read();
	    a[b]+=1;
	}
    }
    for i in 0..m+1{
	if a[i as usize] == n as i32{
	    count+=1;
	}
    }
    println!("{}",count);
}


use std::io::Read;
fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let m: usize = iter.next().unwrap().parse().unwrap();

    let mut h = vec![0; m];

    for _ in 0..n {
        let k: usize = iter.next().unwrap().parse().unwrap();
        for _ in 0..k {
            let a: usize = iter.next().unwrap().parse().unwrap();
            h[a - 1] += 1;
        }
    }

    println!("{}", h.iter().filter(|&x| *x == n).count());
}


use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {n: isize, l: isize};
    let mut v: Vec<i32> = Vec::new();

    for i in l..l + n {
        v.push(i as i32);
    }

    let mut min: i32 = 1_000_000;
    let mut x: i32 = 0;

    for v_i in v.iter() {
        if min > v_i.abs() {
            min = v_i.abs();
            x = *v_i;
        }
    }

    println!("{}", v.iter().sum::<i32>() - x);
}


use proconio::input;
use proconio::marker::Usize1;

fn main() {
   input! {
     n: usize,
     m: usize,
     ks: [[Usize1]; n]
   }
   let mut cnt = vec![0; m];
   let mut ans = 0;
   for k in ks.iter() {
     for &c in k.iter() {
       cnt[c] += 1;
     }
   }
   for v in cnt {
     if v == n {
       ans += 1;
     }
   }
   println!("{:?}", ans);
}


//! https://github.com/hatoo/competitive-rust-snippets
//!
//! MIT License
//!
//! Copyright (c) 2018 hatoo
//!
//! Permission is hereby granted, free of charge, to any person obtaining a copy
//! of this software and associated documentation files (the "Software"), to deal
//! in the Software without restriction, including without limitation the rights
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//! copies of the Software, and to permit persons to whom the Software is
//! furnished to do so, subject to the following conditions:
//!
//! The above copyright notice and this permission notice shall be included in all
//! copies or substantial portions of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//! SOFTWARE.
#![allow(
    unused_imports,
    unused_attributes,
    unused_macros,
    dead_code,
    non_snake_case
)]
use std::cmp::{max, min, Ordering};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::{stdin, stdout, BufWriter, Write};
use std::iter::FromIterator;
#[macro_export]
macro_rules ! get {(@ inner [$ src : expr ] chars ) => {{let mut buf = String :: new () ; $ src . read_line (& mut buf ) . unwrap () ; buf . trim () . chars () . collect ::< Vec < char >> () } } ; (@ inner [$ src : expr ] usize1 ) => {{get ! (@ inner [$ src ] usize ) - 1 } } ; (@ inner [$ src : expr ] [usize1 ] ) => {{get ! (@ inner [$ src ] [usize ] ) . into_iter () . map (| v | v - 1 ) . collect ::< Vec < usize >> () } } ; (@ inner [$ src : expr ] [[usize1 ] ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] [usize1 ] ) ) . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] [usize1 ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] [usize1 ] ) ) . flatten () . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] [[chars ] ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] chars ) ) . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] [chars ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] chars ) ) . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] [($ ($ tt : tt ) ,* ) ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] ($ ($ tt ) ,* ) ) ) . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] ($ ($ tt : tt ) ,* ) ) => {{let mut buf : String = String :: new () ; $ src . read_line (& mut buf ) . unwrap () ; let mut iter = buf . split_whitespace () ; ($ (get ! (@ inner_elem_parse [$ tt ] iter . next () . unwrap () ) , ) * ) } } ; (@ inner [$ src : expr ] [$ t : ty ] ) => {{let mut buf = String :: new () ; $ src . read_line (& mut buf ) . unwrap () ; buf . trim () . split_whitespace () . map (| t | t . parse ::<$ t > () . unwrap () ) . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] [[$ t : ty ] ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] [$ t ] ) ) . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] [$ t : ty ; $ n : expr ] ) => {{(0 ..$ n ) . map (| _ | get ! (@ inner [$ src ] [$ t ] ) ) . flatten () . collect ::< Vec < _ >> () } } ; (@ inner [$ src : expr ] $ t : ty ) => {{let mut buf = String :: new () ; $ src . read_line (& mut buf ) . unwrap () ; buf . trim () . split_whitespace () . next () . unwrap () . parse ::<$ t > () . unwrap () } } ; (@ inner_elem_parse [usize1 ] $ elem : expr ) => {{get ! (@ inner_elem_parse [usize ] $ elem ) - 1 } } ; (@ inner_elem_parse [$ t : ty ] $ elem : expr ) => {{$ elem . parse ::<$ t > () . unwrap () } } ; ($ tt : tt ) => {{use std :: io :: BufRead ; let get_stdin = std :: io :: stdin () ; let mut locked_stdin = get_stdin . lock () ; get ! (@ inner [& mut locked_stdin ] $ tt ) } } ; }
macro_rules ! debug {($ ($ a : expr ) ,* $ (, ) * ) => {# [cfg (debug_assertions ) ] eprintln ! (concat ! ($ ("| " , stringify ! ($ a ) , "={:?} " ) ,*, "|" ) , $ (&$ a ) ,* ) ; } ; }
macro_rules ! echo {($ ($ a : expr ) ,* ) => {let mut s = Vec :: new () ; $ (s . push (format ! ("{}" , $ a ) ) ; ) * println ! ("{}" , s . join (" " ) ) ; } }
#[macro_export]
macro_rules ! chmin {($ base : expr , $ ($ cmps : expr ) ,+ $ (, ) * ) => {{let cmp_min = min ! ($ ($ cmps ) ,+ ) ; if $ base > cmp_min {$ base = cmp_min ; true } else {false } } } ; }
#[macro_export]
macro_rules ! chmax {($ base : expr , $ ($ cmps : expr ) ,+ $ (, ) * ) => {{let cmp_max = max ! ($ ($ cmps ) ,+ ) ; if $ base < cmp_max {$ base = cmp_max ; true } else {false } } } ; }
#[macro_export]
macro_rules ! min {($ a : expr $ (, ) * ) => {{$ a } } ; ($ a : expr , $ b : expr $ (, ) * ) => {{std :: cmp :: min ($ a , $ b ) } } ; ($ a : expr , $ ($ rest : expr ) ,+ $ (, ) * ) => {{std :: cmp :: min ($ a , min ! ($ ($ rest ) ,+ ) ) } } ; }
#[macro_export]
macro_rules ! max {($ a : expr $ (, ) * ) => {{$ a } } ; ($ a : expr , $ b : expr $ (, ) * ) => {{std :: cmp :: max ($ a , $ b ) } } ; ($ a : expr , $ ($ rest : expr ) ,+ $ (, ) * ) => {{std :: cmp :: max ($ a , max ! ($ ($ rest ) ,+ ) ) } } ; }
const BIG_STACK_SIZE: bool = true;
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}
fn solve() {
    let (n, m) = get!((usize, usize));
    let mut loved = HashSet::new();
    for i in 1..(m + 1) {
        loved.insert(i);
    }
    for _ in 0..n {
        let ka = get!([usize]);
        let mut set = HashSet::new();
        for a in ka.into_iter().skip(1) {
            set.insert(a);
        }
        loved = loved.intersection(&set).copied().collect();
    }
    echo!(loved.len());
}


let NM: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
var num: [Int] = Array(repeating: 0, count: NM[1])
for _ in 1...NM[0] {

    for A in readLine()!.split(separator: " ").map({ Int($0)! }).dropFirst() {
        num[A-1] += 1
    }
}
var res: Int = 0
for a in num {
    if a == NM[0] { res += 1}
}
print(res)


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatedValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i + 1])! - 1
        cnt[A] += 1
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatedValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i+1])! - 1
        cnt[A] += 1
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatedValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i+1])!
        cnt[i] = A
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatedValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i])!
        cnt[i] = A
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatingValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i])!
        cnt[i] = A
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)


const main = (input) => {
  const lines = input.trim().split("\n");
  const [N, M] = lines[0].split(' ').map(x => parseInt(x));
  const A = [].concat(...lines.slice(1).map(line => line.split(' ').slice(1))).map(food => parseInt(food) - 1);

  const countMap = Array(M).fill(0);
  A.forEach(food => countMap[food]++);
  const ans = countMap.filter(count => count === N).length

  console.log(ans)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const t={input:require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/),n:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.n())}return a}else{const a=t.input[0];t.input.shift();return Number(a)}},s:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.s())}return a}else{const a=t.input[0];t.input.shift();return String(a)}},c:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.c())}return a}else{let a=t.input[0].split('');const b=a[0];a.shift();if(a.length>0){t.input[0]=a.join('')}else{t.input.shift()}return String(b)}},o:(...arg)=>{console.log(...arg)},abs:(a)=>{return Math.abs(a)},min:(...a)=>{return Math.min(...a)},max:(...a)=>{return Math.max(...a)},floor:(a)=>{return Math.floor(a)},asc:(ar:number[])=>{return ar.sort((a,b)=>{return a-b})},desc:(ar:number[])=>{return ar.sort((a,b)=>{return b-a})},sw:(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]}};
const main=()=>{
  let n=t.n()
  let nr=new Array(t.n())
  nr.fill(0)
  for(let i=0;i<n;i++){
    let jl=t.n()
    for(let j=0;j<jl;j++){
      nr[t.n()-1]++
    }
  }
  let ans=0
  for(let i=0;i<nr.length;i++){
    if(nr[i]==n)ans++
  }
  t.o(ans)
}
main()


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const [head, ...rest] = stdin.split('\n').filter(e=>e)

const [n, m] = head.split(' ').map(Number)

const ka = rest.map(e=>e.split(' ').map(Number))

let commons = []

ka.forEach((e,i)=>{
  const [k, ...a] = e

  if(i === 0){
    commons = a
  } else {
    const filtered = a.filter(v => {
      return commons.indexOf(v) > -1
    })

    commons = filtered
  }
})

console.log(commons.length)


const main = (input) => {
  const lines = input.trim().split("\n");
  const [N, M] = lines[0].split(' ').map(x => parseInt(x));
  const A = lines.slice(1).flatMap(line => line.split(' ').slice(1).map(food => parseInt(food) - 1));

  const countMap = Array(M).fill(0);
  A.forEach(food => countMap[food]++);
  const ans = countMap.filter(count => count === N).length

  console.log(ans)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input: string) => {
  const lines = input.split("\n").slice(1);
  let K = [];
  let result = 0;

  for (let i = 0; i < lines.length; i++) {
    K.push(lines[i].split(" ").map(str => parseInt(str)))
    K[i].shift();
  }

  for (let i = 0; i < K.length; i++) {
    let answer = 0;

    for (let j = 0; j < K[i].length; j++) {
      if(K[i].indexOf(K[i][j]) >= 0) {
        answer += 1;
      }
    }

    if(answer === K.length) {
      result += 1;
    }
  }

  if(K.length === 1) {
    result = K[0].length;
  }

  console.log(result)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input: string) => {
  const lines = input.split("\n").slice(1);
  let K = [];
  let result = 0;

  for (let i = 0; i < lines.length; i++) {
    K.push(lines[i].split(" ").map(str => parseInt(str)))
    K[i].shift();
  }

  for (let i = 0; i < K.length; i++) {
    let answer = 0;

    for (let j = 0; j < K[i].length; j++) {
      if(K[i].indexOf(K[i][j]) >= 0) {
        answer += 1;
      }
    }

    if(answer === K.length) {
      result += 1;
    }

    if(K.length === 1) {
      result = K[0].length;
    }
  }

  console.log(result)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


def main():
    _ = input()
    a = list(map(int, input().split()))
    max_height = 0
    ans = 0
    for height in a:
        if max_height <= height:
            max_height = height
        else:
            ans += max_height - height
    print(ans)

if __name__ == "__main__":
    main()


def probC():
    N = input()
    A = map(int, input().split())

    step = 0
    max_height = 0
    for i in A:
        if max_height < i:
            max_height = i
        else:
            step += max_height - i

    print(step)

def main():
    probC()

if __name__ == '__main__':
    main()


def main():
    N = int(input())
    A = list(map(int, input().split()))

    tallest = A[0]
    ans = 0

    for height in A:
        if height < tallest:
            ans += tallest - height
        elif height > tallest:
            tallest = height

    print(ans)

if __name__ == "__main__":
    main()


N=int(input())
A=list(map(int,input().split()))
a=0
s=[]
for i in A:
  if i<a:
    s.append(a-i)
    print(s)
  else:
    a=i
print(sum(s))


N=int(input())
A=list(map(int,input().split()))
a=0
s=[]
for i in A:
  if i<a:
    s.append(a-i)
    a=i
  else:
    a=i
print(sum(s))


N=int(input())
A=list(map(int,input().split()))
a=0
s=[]
for i in A:
  if i<a:
    s.append(i-a)
    a=i
  else:
    a=i
print(sum(s))


import java.util.*;
import java.io.*;
public class Main{

    public static void main(String [] args) throws IOException{
        FastScanner sc=new FastScanner();
        int n=sc.nextInt();
        long [] a=sc.nextLongArray(n);
        long max=a[0],ans=0;
        for(int i=1;i<n;i++){
            ans+=Math.max(max-a[i],0);
            max=Math.max(max,a[i]);
        }
        System.out.println(ans);
    }
}

class FastScanner{
    private int BUFFER_SIZE = 1 << 16;

   private  DataInputStream din;

   private  byte[] buffer;

   private int bufferPointer, bytesRead;

   public FastScanner() {
       din = new DataInputStream(System.in);
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public FastScanner( String file_name) throws IOException {
       din = new DataInputStream(new FileInputStream(file_name));
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public String readLine() throws IOException {
        byte[] buf = new byte[64];
       int cnt = 0, c;
       while ((c = read()) != -1) {
           if (c == '\n')
               break;
           buf[cnt++] = (byte) c;
       }
       return new String(buf, 0, cnt);
   }

   public String next() throws IOException{

       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }

        StringBuilder builder = new StringBuilder();
       builder.append((char)c);
       c = read();
       while(!Character.isWhitespace(c)){
           builder.append((char)c);
           c = read();
       }

       return builder.toString();
   }

   public int nextInt() throws IOException {
       int ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (neg)
           return -ret;
       return ret;
   }

   public int[] nextIntArray( int n) throws IOException {
        int arr[] = new int[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextInt();
       }
       return arr;
   }

   public long nextLong() throws IOException {
       long ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');
       if (neg)
           return -ret;
       return ret;
   }

   public long[] nextLongArray( int n) throws IOException {
        long arr[] = new long[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextLong();
       }
       return arr;
   }

   public char nextChar() throws IOException{
       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }
       return (char) c;
   }

   public double nextDouble() throws IOException {
       double ret = 0, div = 1;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();

       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (c == '.') {
           while ((c = read()) >= '0' && c <= '9') {
               ret += (c - '0') / (div *= 10);
           }
       }

       if (neg)
           return -ret;
       return ret;
   }

   public double[] nextDoubleArray( int n) throws IOException {
        double arr[] = new double[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextDouble();
       }
       return arr;
   }

   private void fillBuffer() throws IOException {
       bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
       if (bytesRead == -1)
           buffer[0] = -1;
   }

   private byte read() throws IOException {
       if (bufferPointer == bytesRead)
           fillBuffer();
       return buffer[bufferPointer++];
   }

   public void close() throws IOException {
       if (din == null)
           return;
       din.close();
   }

}


import java.io.*;
import java.util.*;

public class Main {
	static final StdIn in = new StdIn();
	static final PrintWriter out = new PrintWriter(System.out);

	public static void main(String[] args) {
        int N = in.nextInt();

        long arr[] = new long[N];
        for (int i = 0; i < N; i++) {
            arr[i] = in.nextLong();
        }

        long first = arr[0];
        long res = 0;

        for (int i = 1; i < arr.length; i++) {
            long diff = first - arr[i];
            if(diff > 0) {
                  res += diff;
            }
            if(first < arr[i]) {
                first = arr[i];
            }
        }
        out.println(res);
        // long res = 0;

        // while(N >= 0) {
        //     long d = N % 10;
        //     res += d;
        //     N = N/10;
        // }

        // if(res%9 == 0) {
        //     out.println("Yes");
        // } else {
        //     out.println("No");
        // }
		out.close();
    }

    static class Solver {
		Solver() {

        }

    }

    static long factorial(long x) {
        if(x <= 1) {
            return 1;
        }
        long res = 2;
        for (int i = 3; i <= x; i++) {
            res = res * i;
        }
        return res;
    }

    static long gcdOfFactorial(long a, long b) {
        if (b == 0)
            return a;
        return gcdOfFactorial(b, a % b);
    }

	static class StdIn {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;
		public StdIn() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public StdIn(InputStream in) {
			try{
				din = new DataInputStream(in);
			} catch(Exception e) {
				throw new RuntimeException();
			}
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public String next() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == ' ' || c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c=read();
			}
			return s.toString();
		}
		public String nextLine() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c = read();
			}
			return s.toString();
		}
		public int nextInt() {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}
		public int[] readIntArray(int n, int os) {
			int[] ar = new int[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextInt()+os;
			return ar;
		}
		public long nextLong() {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}
		public long[] readLongArray(int n, long os) {
			long[] ar = new long[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextLong()+os;
			return ar;
		}
		public double nextDouble() {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (c == '.')
				while ((c = read()) >= '0' && c <= '9')
					ret += (c - '0') / (div *= 10);
			if (neg)
				return -ret;
			return ret;
		}
		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}
		private byte read() {
			try{
				if (bufferPointer == bytesRead)
					fillBuffer();
				return buffer[bufferPointer++];
			} catch(IOException e) {
				throw new RuntimeException();
			}
		}
		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
}


import org.omg.CORBA.INTERNAL;

import java.io. *;
import java.util.*;
import static java.lang.Math.*;
public class Main {

    static final FastReader sc = new FastReader(System.in);
    static final PrintWriter pw = new PrintWriter(System.out);

    static int visited[];
    static ArrayList<ArrayList<Integer>> adjlist;
    static class edge implements  Comparator<edge>{
        int dest;
        int cost;

        public edge(int dest, int cost) {
            this.dest = dest;
            this.cost = cost;
        }

        @Override
        public int compare(edge o1, edge o2) {
            return o1.cost-o2.cost;
        }
    }

    static int dist[];
    static int nodesinSubtree[];
    static int color[];
    static ArrayList<Integer> leaves;
    static ArrayList<PriorityQueue<Integer>> apq;

    static class Graph {
        int V;
        ArrayList<ArrayList<edge>> adj;
        PriorityQueue<edge> pq;
        boolean visited[];

        public Graph(int V) {
            this.V = V;
            adj = new ArrayList<>(V);
            pq = new PriorityQueue<>(V, new edge(-1, -1));
            dist = new int[V];
            visited = new boolean[V];
            for (int i = 0; i < V; i++) {
                dist[i] = Integer.MAX_VALUE;
                adj.add(i, new ArrayList<>());
            }
        }

        void addedge(int u, int v, int w) {
            adj.get(u).add(new edge(v, w));
            adj.get(v).add(new edge(u, w));
        }

        void rDfs(int src, int e) {
            if(adj.get(src).size()==0){
                leaves.add(src);
            }

            for (int i = 0; i < adj.get(src).size(); i++) {
                if (adj.get(src).get(i).dest == e) {
                    continue;
                }
                rDfs(adj.get(src).get(i).dest, src);
            }
        }

        PriorityQueue<Integer> Dfs(int src, int e, PriorityQueue<Integer> pq) {
            if(adj.get(src).size()==0){
                if(src!=0 && !pq.isEmpty()){
                    pq.remove(adj.get(src).get(e).cost);
                }
            }

            for (int i = 0; i < adj.get(src).size(); i++) {
                if (adj.get(src).get(i).dest == e) {
                    continue;
                }
                if (adj.get(src).get(i).dest == 1) {
                    pq.add(adj.get(src).get(i).cost);
                    return pq;
                }
                pq.add(adj.get(src).get(i).cost);
                Dfs(adj.get(src).get(i).dest, src, pq);
            }

            return pq;

        }

/*
        void dijkstra(int src){
            for(int i=0; i<V; i++){
                dist[i] = Integer.MAX_VALUE;
            }
            dist[src] = 0;
            pq.add(new edge(src,0));
            while (!pq.isEmpty()){
                int u = pq.poll().dest;
                for(int i=0; i<adj.get(u).size(); i++){
                    int v = adj.get(u).get(i).dest;
                    int w = adj.get(u).get(i).cost;
                    if(dist[u]+w<=dist[v]){
                        dist[v] = dist[u] + w;
                        pq.add(new edge(v,dist[v]));
                    }
                }
            }

        }

    }

 */
    }

    static  int I[];
    static  int  L[];
    static int LIS(int n, int arr[]){
        I = new int[n+1];
        L = new int[n];
        I[0] = Integer.MIN_VALUE;
        for(int i=1;i<=n; i++){
            I[i] = Integer.MAX_VALUE;
        }

        int lisLength = 1;

        int cm = 0;

        for(int i=n-1; i>=0; i--) {
            int low = 1;
            int high = lisLength;
            int mid = 0;
            while (low < high) {
                mid = (low + high) >> 1;
                if (I[mid] <= arr[i]) {
                    high = mid;
                } else {
                    low = mid + 1;
                }
            }

            if(I[high]==arr[i]){
                cm++;
            }
            I[high] = arr[i];
            L[i] = high;
            if(lisLength<=high){
                lisLength++;
            }
        }
        return 1;
    }

    public static long gcd(long a, long b)
    {
        if (a == 0)
            return b;

        return gcd(b%a, a);
    }

    public static long lcm(long a, long b)
    {
        return (a*b)/gcd(a, b);
    }

    static long nCr(long n, long r)
    {
        return fact(n) / (fact(r) * fact(n - r));
    }

    // Returns factorial of n
    static long fact(long n)
    {
        long res = 1;
        for (int i = 2; i <= n; i++)
            res = (res * i)%MOD;
        return res;
    }

    static int MOD = 1000000007;
    static int power(int x, int y, int p)
    {

        // Initialize result
        int res = 1;

        // Update x if it is more than or
        // equal to p
        x = x % p;

        while (y > 0)
        {

            // If y is odd, multiply x
            // with result
            if (y % 2 == 1)
                res = (res * x) % p;

            // y must be even now
            y = y >> 1; // y = y/2
            x = (x * x) % p;
        }

        return res;
    }

    // Returns n^(-1) mod p
    static int modInverse(int n, int p)
    {
        return power(n, p-2, p);
    }

    static int nCrModPFermat(int n, int r,
                             int p)
    {

        if (r == 0)
            return 1;

        int[] fac = new int[n+1];
        fac[0] = 1;

        for (int i = 1 ;i <= n; i++)
            fac[i] = fac[i-1] * i % p;

        return (fac[n]* modInverse(fac[r], p)
                % p * modInverse(fac[n-r], p)
                % p) % p;
    }

    static int[] phi;

    static void generatePhi(int n){
        phi = new int[n+1];

        for(int i = 0; i<=n; i++){
            phi[i] = i;
        }

        for(int i=2; i<=n; i++){
            if(phi[i]==i){
                for(int j= i; j<=n; j+=i){
                    phi[j] -= (phi[j]/i);
                }
            }
        }
    }

    static int gcdCount(int n, int d){
        return phi[n/d];
    }

    static boolean prime[];
    static int smallestFactor[];

    static void sieveOfEratosthenes(int n)
    {
        prime = new boolean[n+1];
        smallestFactor = new int[n+1];

        smallestFactor[1] = 1;
        for(int i=2;i<n;i++) {
            prime[i] = true;
            smallestFactor[i] = i;
        }

        for(int p = 2; p*p <=n; p++)
        {
            if(prime[p])
            {
                smallestFactor[p] = p;
                for(int i = p*p; i <= n; i += p) {
                    prime[i] = false;
                    smallestFactor[i] = min(p,smallestFactor[i]);
                }
            }
        }

    }

    static double Logx(double n, int x){
        return log(n)/log(x);
    }

    static boolean isPrime(long n){
        if(n<2){
            return false;
        }
        for(int i = 2; i*i<=n; i++){
            if(n%i==0){
                return false;
            }
        }
        return true;
    }

    static int sumOfDigits(int n){
        int digitSum = 0;
        while (n>0){
            digitSum+=n%10;
            n/=10;
        }
        return digitSum;
    }

    static boolean checkSum(PriorityQueue<Integer> pq, long s){
        long sum = 0;
        while (!pq.isEmpty()){
            sum+= pq.poll();
        }
        if(sum>s){
            return false;
        }

        return true;

    }

    public static void main(String[] args) {

       int n = sc.nextInt();

       int a[] = new int[n];

       for(int i =0; i<n; i++){
           a[i] = sc.nextInt();
       }

       long sum = 0;

       for(int i = 0; i<n-1; i++){
           if(a[i+1]<a[i]){
               sum += (a[i]-a[i+1]);
               a[i+1] = a[i];
           }
       }

       pw.println(sum);

        pw.flush();

    }

    static void debug(Object...obj) {
        System.err.println(Arrays.deepToString(obj));
    }

    static class FastReader {
        InputStream is;
        private byte[] inbuf = new byte[1024];
        private int lenbuf = 0, ptrbuf = 0;

        public FastReader(InputStream is) {
            this.is = is;
        }

        public int readByte(){
            if(lenbuf == -1)throw new InputMismatchException();
            if(ptrbuf >= lenbuf){
                ptrbuf = 0;
                try {
                    lenbuf = is.read(inbuf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if(lenbuf <= 0)
                    return -1;
            }
            return inbuf[ptrbuf++];
        }
        public boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }
        public int skip() {
            int b;
            while ((b = readByte()) != -1 && isSpaceChar(b)) ;
            return b;
        }
        public String next(){
            int b = skip();
            StringBuilder sb = new StringBuilder();
            while(!(isSpaceChar(b))) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }
        public String nextLine(){
            int b = readByte();
            StringBuilder sb = new StringBuilder();
            while(b != '\n' || b != '\r'){
                sb.appendCodePoint(b);
            }
            return sb.toString();
        }
        public int nextInt() {
            int num = 0, b;
            boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            while (true) {
                if (b >= '0' && b <= '9') {
                    num = (num << 3) + (num << 1) + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }
        public long nextLong() {
            long num = 0;
            int b;
            boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            while (true) {
                if (b >= '0' && b <= '9') {
                    num = (num << 3) + (num << 1) + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }
        public double nextDouble() {
            return Double.parseDouble(next());
        }
        public char[] next(int n){
            char[] buf = new char[n];
            int b = skip(), p = 0;
            while (p < n && !(isSpaceChar(b))) {
                buf[p++] = (char) b;
                b = readByte();
            }
            return n == p ? buf : Arrays.copyOf(buf, p);
        }
        public char nextChar () {
            return (char) skip();
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        int n=sc.nextInt();
        int a[]=sc.readArray(n);
        int max=a[0];
        int sum=0;
        for (int i=1;i<n;i++){
            max=Math.max(a[i],max);
            sum+=max-a[i];

        }
        System.out.println(sum);

        out.flush();

    }

    static void sort(int[] a) {
        ArrayList<Integer> l=new ArrayList<>();
        for (int i:a) l.add(i);
        Collections.sort(l);
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }
    static void sortReverse(long[] a) {
        ArrayList<Long> l=new ArrayList<>();
        for (long i:a) l.add(i);
//        Collections.sort.(l);
        Collections.sort(l,Collections.reverseOrder());
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }

    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long[] readArrayLong(long n) {
            long[] a=new long[(int)n];
            for (int i=0; i<n; i++) a[i]=nextLong();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }
    }

}


import java.util.*;
import java.io.*;
import java.lang.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] arr = new int[n];

        int ans = 0;

        for (int i = 0; i<n; i++){
            arr[i] = sc.nextInt();
        }

        for (int i = 1; i<n; i++){
            if (arr[i] < arr[i-1]){
                ans += (arr[i-1]-arr[i]);
                arr[i] = arr[i-1];
            }
        }
        System.out.println(ans);
    }
}


import java.util.*;
import java.io.*;
import java.lang.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] arr = new int[n];

        int ans = 0;

        for (int i = 0; i<n; i++){
            arr[i] = sc.nextInt();
        }

        for (int i = 1; i<n; i++){
            if (arr[i] < arr[i-1]){
                ans = ans + (arr[i-1]-arr[i]);
                arr[i] = arr[i-1];
            }
        }
        System.out.println(ans);
    }
}


#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	if ((tmp & ma0) ^ ma0) {
		int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
		tmp = tmp << dig & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += (72 - dig >> 3);
	}
	else {
		tmp = tmp & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += 8;
		if ((ct = *ci++) >= '0') {
			tmp = tmp * 10 + ct - '0';
			if (*ci++ == '0') {
				tmp = tmp * 10;
				ci++;
			}
		}
	}
	return tmp;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint();
	int saidai = 0;
	ll kotae = 0;
	rep(i, N) {
		int a = getint();
		if (saidai < a) {
			saidai = a;
		}
		else {
			kotae += saidai - a;
		}
	}
	printf("%lld\n", kotae);

	Would you please return 0;
}


/*                         _
                        _ooOoo_
                       o8888888o
                       88" . "88
                       (| -_- |)
                       O\  =  /O
                    ____/`---'\____
                  .'  \\|     |//  `.
                 /  \\|||  :  |||//  \
                /  _||||| -:- |||||_  \
                |   | \\\  -  /'| |   |
                | \_|  `\`---'//  |_/ |
                \  .-\__ `-. -'__/-.  /
              ___`. .'  /--.--\  `. .'___
           ."" '<  `.___\_<|>_/___.' _> \"".
          | | :  `- \`. ;`. _/; .'/ /  .' ; |
          \  \ `-.   \_\_`. _.'_/_/  -' _.' /
===========`-.`___`-.__\ \___  /__.-'_.'_.-'================

                  Please give me AC.
*/

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <string>
#include <sstream>
#include <complex>
#include <bitset>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <chrono>
#include <random>

using namespace std;

using int64 = long long;
using uint64 = unsigned long long;
using vi = vector<int>;
using vl = vector<int64>;
using pii = pair<int, int>;
using pll = pair<int64, int64>;

#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define all(v) (v).begin(), (v).end()
#define print(x) cout << (x) << '\n'
#define print2(x, y) cout << (x) << ' ' << (y) << '\n'
#define print3(x, y, z) cout << (x) << ' ' << (y) << ' ' << (z) << '\n'
#define printn(v) rep(i, (v).size() - 1) cout << (v)[i] << ' '; cout << (v)[n - 1] << '\n';
#ifdef ONLINE_JUDGE
#define debug(x)
#define debug2(x, y)
#define debug3(x, y, z)
#define dbg(v)
#else
#define debug(x) cerr << #x << ": " << (x) << '\n'
#define debug2(x, y) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << '\n'
#define debug3(x, y, z) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << ", " << #z << ": " << (z) << '\n'
#define dbg(v) for (size_t _ = 0; _ < v.size(); ++_){cerr << #v << "[" << _ << "] : " << v[_] << '\n';}
#endif

// constant
const int INF = (1<<30) - 1;
const int64 INF64 = (1LL<<62) - 1;

template<typename T> T gcd(T a, T b) {
    if (a < b) return gcd(b, a);
    T r;
    while ((r = a % b)) {
        a = b;
        b = r;
    }
    return b;
}

template<typename T> T lcm(const T a, const T b) {
    return a / gcd(a, b) * b;
}

template<typename T> bool chmin(T& a, const T& b) {
    if (a > b) return a = b, true; else return false;
}

template<typename T> bool chmax(T& a, const T& b) {
    if (a < b) return a = b, true; else return false;
}

// End of template.
// begin fast io
template <typename IStream = decltype(cin), typename OStream = decltype(cout)>
struct FastIO {
    char *buf, *OUT, *out;
    OStream& os;

    FastIO(size_t input_size = 1e7, size_t output_size = 1e7): os(cout) {
        buf = new char[input_size];
        OUT = new char[output_size];
        out = OUT;
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cin.read(buf, input_size);
    }

    FastIO(IStream& in, OStream& out, size_t input_size = 1e7, size_t output_size = 1e7): os(out) {
        buf = new char[input_size];
        OUT = new char[output_size];
        this-> out = OUT;
        in.read(buf, input_size);
    }

    ~FastIO() {
        os.write(OUT, out - OUT);
    }

    char readc() {
        return *buf++;
    }

    template<typename T>
    void readui(T &n) {
        n = 0;
        char c = readc();
        for (; '0' <= c && c <= '9'; c = readc())
            n = 10 * n + c - '0';
    }

    template<typename T>
    void readi(T &n) {
        bool negative = false;
        if (*buf == '-') negative = true, buf++;
        readui(n);
        if (negative) n = -n;
    }

    template<typename T>
    void readuf(T &x) {
        x = 0;
        T y = 0;
        int z = 0;
        char c = readc();
        for (; '0' <= c && c <= '9'; c = readc())
            x = 10 * x + c - '0';
        if (buf[-1] == '.')
            for (; '0' <= c && c <= '9'; c = readc(), ++z)
                y = 10 * y + c - '0';
        x += y / pow(10, z);
    }

    template<typename T>
    void readf(T &x) {
        bool negative = false;
        if (*buf == '-') negative = true, buf++;
        readuf(x);
        if (negative) x = -x;
    }

    string_view reads() {
        const char *begin = buf;
        char c;
        while (c = readc(), c >= '!') {}
        return string_view(begin, buf - begin - 1);
    }

    string_view readline() {
        const char *begin = buf;
        while (readc() != '\n') {}
        return string_view(begin, buf - begin - 1);
    }

    void writec(const char c) {
        *out++ = c;
    }

    void writes(const string& s) {
        memcpy(out, s.c_str(), s.size());
        out += s.size();
    }

    void writes(const string_view& s) {
        memcpy(out, s.data(), s.size());
        out += s.size();
    }

    constexpr static char digit_pairs[] = {
            "00010203040506070809"
            "10111213141516171819"
            "20212223242526272829"
            "30313233343536373839"
            "40414243444546474849"
            "50515253545556575859"
            "60616263646566676869"
            "70717273747576777879"
            "80818283848586878889"
            "90919293949596979899"
    };

    template<typename T>
    void writeui(T n) {
        if (n == 0) { writec('0'); return; }
        int size;
        if (n >= 1e12) {
            if (n >= 1e16) {
                if (n >= 1e18) {
                    if (n >= 1e19) size = 20;
                    else size = 19;
                } else {
                    if (n >= 1e17) size = 18;
                    else size = 17;
                }
            } else {
                if (n >= 1e14) {
                    if (n >= 1e15) size = 16;
                    else size = 15;
                } else {
                    if (n >= 1e13) size = 14;
                    else size = 13;
                }
            }
        } else if (n >= 1e4) {
            if (n >= 1e8) {
                if (n >= 1e10) {
                    if (n >= 1e11) size = 12;
                    else size = 11;
                } else {
                    if (n >= 1e9) size = 10;
                    else size = 9;
                }
            } else {
                if (n >= 1e6) {
                    if (n >= 1e7) size = 8;
                    else size = 7;
                } else {
                    if (n >= 1e5) size = 6;
                    else size = 5;
                }
            }
        } else {
            if (n >= 1e2) {
                if (n >= 1e3) size = 4;
                else size = 3;
            } else {
                if (n >= 1e1) size = 2;
                else size = 1;
            }
        }
        char *c = out + size;
        out += size;
        while (n >= 100) {
            int x = n % 100;
            n /= 100;
            *--c = digit_pairs[2 * x + 1];
            *--c = digit_pairs[2 * x];
        }
        while (n > 0) {
            *--c = '0' + (n % 10);
            n /= 10;
        }
    }

    template<typename T>
    void writei(T n) {
        if (n < 0) {
            writec('-');
            writeui(-n);
        } else {
            writeui(n);
        }
    }
};
// end fast io

int main() {
    FastIO io;

    int n;
    io.readui(n);
    int64 t = 0;
    int64 ans = 0;
    io.readui(t);

    rep(i, n - 1) {
        int a;
        io.readui(a);
        if (t < a) {
            t = a;
        } else {
            ans += t - a;
        }
    }

    io.writeui(ans);
    io.writec('\n');

    return 0;
}

/*
  ___   ___ _ __  _ __
 / __| / __| '_ \| '_ \
| (__ | (__| |_) | |_) |
 \___(_)___| .__/| .__/
           |_|   |_|
*/


#pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
template<class S, class T> inline S max_L(S a,T b){
  return a>=b?a:b;
}
inline int my_getchar_unlocked(){
  static char buf[1048576];
  static int s = 1048576;
  static int e = 1048576;
  if(s == e && e == 1048576){
    e = fread_unlocked(buf, 1, 1048576, stdin);
    s = 0;
  }
  if(s == e){
    return EOF;
  }
  return buf[s++];
}
inline void rd(int &x){
  int k;
  int m=0;
  x=0;
  for(;;){
    k = my_getchar_unlocked();
    if(k=='-'){
      m=1;
      break;
    }
    if('0'<=k&&k<='9'){
      x=k-'0';
      break;
    }
  }
  for(;;){
    k = my_getchar_unlocked();
    if(k<'0'||k>'9'){
      break;
    }
    x=x*10+k-'0';
  }
  if(m){
    x=-x;
  }
}
struct MY_WRITER{
  char buf[1048576];
  int s;
  int e;
  MY_WRITER(){
    s = 0;
    e = 1048576;
  }
  ~MY_WRITER(){
    if(s){
      fwrite_unlocked(buf, 1, s, stdout);
    }
  }
}
;
MY_WRITER MY_WRITER_VAR;
void my_putchar_unlocked(int a){
  if(MY_WRITER_VAR.s == MY_WRITER_VAR.e){
    fwrite_unlocked(MY_WRITER_VAR.buf, 1, MY_WRITER_VAR.s, stdout);
    MY_WRITER_VAR.s = 0;
  }
  MY_WRITER_VAR.buf[MY_WRITER_VAR.s++] = a;
}
inline void wt_L(char a){
  my_putchar_unlocked(a);
}
inline void wt_L(long long x){
  int s=0;
  int m=0;
  char f[20];
  if(x<0){
    m=1;
    x=-x;
  }
  while(x){
    f[s++]=x%10;
    x/=10;
  }
  if(!s){
    f[s++]=0;
  }
  if(m){
    my_putchar_unlocked('-');
  }
  while(s--){
    my_putchar_unlocked(f[s]+'0');
  }
}
template<class S, class T> inline S chmax(S &a, T b){
  if(a<b){
    a=b;
  }
  return a;
}
int N;
int A[200000];
int main(){
  int i;
  long long res = 0;
  long long mx = -1;
  rd(N);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=(0);Lj4PdHRW<(N);Lj4PdHRW++){
      rd(A[Lj4PdHRW]);
    }
  }
  for(i=(0);i<(N);i++){
    res +=max_L(mx - A[i], 0);
    chmax(mx, A[i]);
  }
  wt_L(res);
  wt_L('\n');
  return 0;
}
// cLay varsion 20200813-1 [beta]

// --- original code ---
// int N, A[2d5];
// {
//   ll res = 0, mx = -1;
//   rd(N,A(N));
//   rep(i,N){
//     res += max(mx - A[i], 0);
//     mx >?= A[i];
//   }
//   wt(res);
// }


#include<cstdio>
//#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxv = 200005;
const int inf = 1e9 + 7;
int ar[maxv];
int main(){
	//freopen("data.in","r",stdin);
	//freopen("abc176c.out","w",stdout);
	int n;
	scanf("%d",&n);
	ll ans=0;
	for(int i=0;i<n;i++){
		scanf("%d",&ar[i]);
		if(i>0&&ar[i]-ar[i-1]<0){
			ans+=(ar[i-1]-ar[i]);
			ans%=inf;
			ar[i]=ar[i-1];
		}
	}
	printf("%lld\n",ans);
	return 0;
}


#include<cstdio>
//#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxv = 200005;
const int inf = 1e9 + 7;
int ar[maxv];
int main(){
	//freopen("data.in","r",stdin);
	//freopen("abc176c.out","w",stdout);
	int n;
	scanf("%d",&n);
	ll ans=0;
	for(int i=0;i<n;i++){
		scanf("%d",&ar[i]);
		if(i>0&&ar[i]-ar[i-1]<0){
			ans+=(ar[i-1]-ar[i]);
			ans%=inf;
			ar[i]=ar[i-1];
		}
	}
	printf("%d\n",ans);
	return 0;
}


#include<cstdio>
//#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxv = 200005;
const int inf = 1e9 + 7;
int ar[maxv];
int main(){
	//freopen("data.in","r",stdin);
	//freopen("abc176c.out","w",stdout);
	int n;
	scanf("%d",&n);
	int ans=0;
	for(int i=0;i<n;i++){
		scanf("%d",&ar[i]);
		if(i>0&&ar[i]-ar[i-1]<0){
			ans+=(ar[i-1]-ar[i]);
			ar[i]=ar[i-1];
		}
	}
	printf("%d\n",ans);
	return 0;
}


#include <stdio.h>

int read()
{
	char c;
	while((c = getchar()) < 48 || c > 57);
	int x = c - 48;
	while((c = getchar()) > 47 && c < 58) x = x * 10 + c - 48;
	return x;
}

int main()
{
	int n, m, x, i;
	long long ans = 0;

	n = read();
	m = read();
	for(i = 1; i < n; i++){
		x = read();
		if(x >= m) m = x;
		else ans += m - x;
	}
	printf("%lld\n", ans);

	return 0;
}


#include <ctype.h>
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }
void rsorta_d32(void *base, const int count, const int size, const int index){
	typedef int32_t rsort_t;
	rsort_t (*a)[size] = (rsort_t(*)[size])base;
	rsort_t (*b)[size] = (rsort_t(*)[size])malloc(count*size*sizeof(rsort_t));
	int c[0x100];
	for(int k=0; k<4; k++){
		memset(c, 0, sizeof(c)); for(int i=0; i<count; i++){ c[(a[i][index]>>(k<<3))&0xFF]++; } for(int i=1; i<0x100; i++) c[i]+=c[i-1]; for(int i=count-1; i>=0; i--){ int to=--c[(a[i][index]>>(k<<3))&0xFF]; for(int j=0; j<size; j++){ b[to][j]=a[i][j]; } }{rsort_t(*t)[size]=a; a=b; b=t;}
	}
	free(b);
}

int a[200000];
int main(void){
	int n=nextint();
	for(int i=0; i<n; i++){
		a[i]=nextint();
	}
	int h=a[0];
	long ans=0;
	for(int i=1; i<n; i++){
		if(a[i]>h){
			h=a[i];
		}else{
			ans+=h-a[i];
		}
	}
	printf("%ld\n", ans);
}


#include<stdio.h>
#include<stdlib.h>

int main(){
    int N;
    scanf("%d%*c",&N);
    char *s = (char *)malloc(11 * N * sizeof(char));
    char *ms = s;
    fgets(s,11*N,stdin);
    unsigned long int max = 0;
    unsigned long int sum = 0;
    for(int i = 0;i < N; i++){
        int n;
        unsigned long int a;
        int j = 0;
        for(j = 0; j < 11; j++){
            if(s[j] == ' '){

                s[j] = '\0';
                break;
            }
        }
        a = (unsigned long int)atoi(s);
        if(max > a){
            sum += max - a;
        }else
        {
            max = a;
        }
        if(i<N-1)
        s = &s[j+1];
    }
    free(ms);
    printf("%ld\n",sum);
    return 0;
}


#include <stdio.h>
#include <stdlib.h>
int	max(int a, int b)
{
	return ((a > b) ? a : b);
}
int	main(void)
{
	int	N;
	int	*A;
	int	res = 0;
	int	m = 0;
	int	i;

	scanf("%d", &N);
	A = malloc(sizeof(int) * N);
	for (i = 0; i < N; i++)
		scanf("%d", &A[i]);
	for (i = 0; i < N; i++)
	{
		m = max(m, A[i]);
		res += m - A[i];
	}
	printf("%lld\n", res);
	free(A);
	return (0);
}


#include <stdio.h>
#include <stdlib.h>

int	main(void)
{
	int	N;
	int	*A, *B;
	long	res = 0;
	int	m;
	int	i;

	scanf("%d", &N);
	A = malloc(sizeof(int) * N);
	for (i = 0; i < N; i++)
		scanf("%d", &A[i]);
	m = A[0];
	B = malloc(sizeof(int) * (N - 1));
	for (i = 0; i < N - 1; i++)
	{
		if (m > A[i + 1])
			B[i] = m - A[i + 1];
		else
		{
			m = A[i + 1];
			B[i] = 0;
		}
	}
	for (i = 0; i < N - 1; i++)
		res += B[i];
	printf("%d\n", res);
	free(A);
	free(B);
	return (0);
}


#include <stdio.h>
#include <stdlib.h>

int	main(void)
{
	int	N;
	int	*A, *B;
	int	res = 0;
	int	m;
	int	i;

	scanf("%d", &N);
	A = malloc(sizeof(int) * N);
	for (i = 0; i < N; i++)
		scanf("%d", &A[i]);
	m = A[0];
	B = malloc(sizeof(int) * (N - 1));
	for (i = 0; i < N - 1; i++)
	{
		if (m > A[i + 1])
			B[i] = m - A[i + 1];
		else
		{
			m = A[i + 1];
			B[i] = 0;
		}
	}
	for (i = 0; i < N - 1; i++)
		res += B[i];
	printf("%d\n", res);
	free(A);
	free(B);
	return (0);
}


function Main(input) {
	const col = input.split("\n");
	const N = parseInt(col[0], 10);
	let row = col[1].split(" ");
	for(let s=0; s < row.length; s++){
		row[s] = parseInt(row[s], 10);
	}
	let tmp = row[0];
	let cnt = 0;
	if(row.length > 1){
		for(let i = 1; i < row.length; i++){
			if(tmp > row[i]){
				cnt += tmp - row[i];
			} else {
				tmp = row[i];
			}
		}
	}
	console.log(cnt);
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	const inputLines = input.split("\n");
	const line0 = inputLines[0];
	const line0vars = line0.split(" ");
	const line1 = inputLines[1];
	const line1vars = line1.split(" ");

	const n = parseInt(line0vars[0], 10);

	var result = 0;
	var current = 0;

	for (var i = 0; i < n; i++) {
		const a = parseInt(line1vars[i], 10);
		if (i === 0) {
			current = a;
			continue;
		}
		if (current < a) {
			current = a;
		} {
			result += current - a;
		}
	}

	console.log(result);

	// tmp = input[1].split(" ");
	// //文字列から10進数に変換するときはparseIntを使います
	// var a = parseInt(input[0], 10);
	// var b = parseInt(tmp[0], 10);
	// var c = parseInt(tmp[1], 10);
	// var s = input[2];

	//出力
	// console.log('%d %s',a+b+c,s);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

// node index.js
// 1
// 2 3
// test
// (Ctrl + D)


function main(lines) {
  const N = n();
  const as = na();

  let max = as[0];
  let ans = 0;
  for (let i = 0; i < N; i++) {
    ans += Math.max(max-as[i], 0);
    max = Math.max(max, as[i]);
  }

  return ans;
}

const lines = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");

let lineCount = 0;
const s = () => lines[lineCount++];
const n = () => Number(s());
const b = () => BigInt(s());
const sa = () => s().split(' ');
const na = () => sa().map(Number);
const ba = () => sa().map(BigInt);

const ans = main(lines);
console.log( ans );


function Main(input){
    // 入力値取得
    input = input.split("\n");
    tmp = input[1].split(" ");
    var people = input[0];
    var diff = 0;
    var dai = 0;

    // tmpの数字をループして
    for (var i = 0; i <= people; i++) {
      if((tmp[i+1] - tmp[i]) > 0) {
        diff = tmp[i+1] - tmp[i]
        dai = dai + Math.abs(diff)
      } else {
        dai = dai
      }
    }
    console.log(dai);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
    // 入力値取得
    input = input.split("\n");
    tmp = input[1].split(" ");
    var people = input[0];
    var diff = 0;
    var dai = 0;

    // tmpの数字をループして
    for (var i = 0; i <= people; i++) {
      if((tmp[i+1] - tmp[i]) >= 0) {
        diff = tmp[i+1] - tmp[i]
        dai = dai + Math.abs(diff)
      }
    }
    console.log(dai);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
    // 入力値取得
    input = input.split("\n");
    tmp = input[1].split(" ");
    var people = input[0];
    var result = 0;
    var dai = 0;

    // tmpの数字をループして
    for (var i = 0; i <= people; i++) {
      if((tmp[i+1] - tmp[i]) >= 0) {
        result = tmp[i+1] - tmp[i]
        dai = dai + Math.abs(result)
      }
    }
    console.log(dai);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main
import (
  "bufio"
  "os"
  "strconv"
  "strings"
  "fmt"
)

func Solve() {
  var N int
  var A []int
  NextInt(&N)
  NextIntSlice(&A)
  ans := 0
  prev := A[0]
  for _, a := range A[1:] {
    if a < prev {
      ans += prev - a
    } else {
      prev = a
    }
  }
  Write(ans)
}

func main() {
  Solve()
  Output()
}

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)
func NextLine() string {
  buffer := make([]byte, 0)
  for true {
    line, isPrefix, err := reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func NextInt(A ...*int) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.Atoi(L[i])
  }
}
func NextIntSlice(A *[]int) {
  L := strings.Split(NextLine(), " ")
  if len(L) == 1 && L[0] == "" {
    (*A) = make([]int, 0)
    return
  }
  (*A) = make([]int, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.Atoi(l)
  }
}
func NextFloat(A ...*float64) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.ParseFloat(L[i], 64)
  }
}
func NextFloatSlice(A *[]float64) {
  L := strings.Split(NextLine(), " ")
  if len(L) == 1 && L[0] == "" {
    (*A) = make([]float64, 0)
    return
  }
  (*A) = make([]float64, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.ParseFloat(l, 64)
  }
}
func Write(S ...interface{}) {
  fmt.Fprintln(writer, S...)
}
func WriteIntSlice(A []int) {
  B := make([]interface{}, len(A))
  for i, a := range A { B[i] = a }
  fmt.Fprintln(writer, B...)
}
func Output() {
  _ = writer.Flush()
}
func MaxInt(A ...int) int {
  max := A[0]
  for _, a := range A {
    if max < a { max = a }
  }
  return max
}
func MinInt(A ...int) int {
  min := A[0]
  for _, a := range A {
    if a < min { min = a }
  }
  return min
}
func SumInt(A ...int) int {
  sum := 0
  for _, a := range A {
    sum += a
  }
  return sum
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
//	"time"
)
var (
	N int
	A []int
)

var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

func readLine() string {
    buf := make([]byte, 0, 1000000)
    for {
        l, p, e := rdr.ReadLine()
        if e != nil {
            panic(e)
        }
        buf = append(buf, l...)
        if !p {
            break
        }
    }
    return string(buf)
}

func stringToArr(str string )[]string{
   return strings.Split( str," ")
}

func atoi(str string)int{
	 ret,_ := strconv.Atoi(str)
	 return ret
}
func atoi2(str []string)[]int{

	ret:= make([]int,len(str))

	for i,v := range(str){
		ret[i] = atoi(v)
	}
	return ret
}

func calc (a []int)int64{
	current:= a[0]
	var cnt int64
	cnt = int64(0)
	for i:=1; i< len(a); i++{
		if current > a[i]{
			cnt= cnt + int64(current - a[i])
		}else{
			current = a[i]
		}

	}
	return cnt

}

func main (){
//	start := time.Now()
N= atoi( readLine())
A= atoi2 ( stringToArr(readLine()))

re:= calc(A)

//s:= atoi2 (stringToArr( readLine()))

//N:=s[0]
//X:=s[1]
//T:=s[2]
/*
cnt:=0
for i:=0; i< len(N); i++ {
	n :=  N[i] - '0'
	cnt += int( n)
}
r:="No"

if  cnt % 9 == 0{
	r="Yes"
}*/

fmt.Println(re)

   //n,_ := strconv.Atoi( readLine());
   //l:= strings.Split( readLine(), " ");

   /*
   for i:=0; i<n ;i++ {

   }

   for i:=1; i<n ;i++ {

   }

   for i:=0; i<n ;i++ {
fmt.Println ( person[i].childrenNumber)
   }*/

 //  end := time.Now()
 //  fmt.Printf("%fç§’\n", (end.Sub(start)).Seconds())

}