#include <bits/stdc++.h>

using namespace std;

#define int long long
#define maxn 100010

int dp[maxn][30];

void solve() {
    string s;
    cin >> s;

    int k;
    cin >> k;

    memset(dp, 63, sizeof dp);
    map<char, char> mp;

    for (int i = 0; i < k; i++) {
        string tp;
        cin >> tp;
        mp[tp[0]] = tp[1];
        mp[tp[1]] = tp[0];
    }

    for (int i = 0; i < 26; i++)
        dp[0][i] = 0;
    for (int i = 0; i < s.size(); i++) {
        for (int j = 0; j < 26; j++) {
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 1);
            if (mp[s[i]] - 'a' != j)
                dp[i + 1][s[i] - 'a'] = min(dp[i][j], dp[i + 1][s[i] - 'a']);
        }
    }
    int mn = LLONG_MAX;
    for (int i = 0; i < 26; i++) {
        mn = min(dp[s.size()][i], mn);
    }
    cout << mn;
}

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
//    cin >> t;

    while (t--)
        solve();
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define int long long
#define endl '\n'

void solve() {
    string s;
    cin >> s;

    int k;
    cin >> k;

    map<char, char> mp;
    for (int i = 0; i < k; i++) {
        string tp;
        cin >> tp;
        mp[tp[0]] = tp[1];
        mp[tp[1]] = tp[0];
    }

    int ans = 0;
    for (int i = 0; i < s.size(); i++) {
        map<char, int> cnt;
        bool fl = false;
        while (i < s.size() - 1 and (s[i] == s[i + 1] or s[i] == mp[s[i + 1]])) {
            cnt[s[i]]++;
            i++;
            fl = true;
        }
        cnt[s[i]]++;
        int mx = LLONG_MAX;
        for (auto x: cnt)
            mx = min(mx, x.second);
        if (fl)
            ans += mx;
    }
    cout << ans << endl;
}

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
//    cin >> t;

    while (t--)
        solve();
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define int long long
#define endl '\n'

void solve() {
    string s;
    cin >> s;

    int k;
    cin >> k;

    map<char, char> mp;
    for (int i = 0; i < k; i++) {
        string tp;
        cin >> tp;
        mp[tp[0]] = tp[1];
        mp[tp[1]] = tp[0];
    }

    int ans = 0;
    for (int i = 0; i < s.size(); i++) {
        map<char, int> cnt;
        bool fl = false;
        while (i < s.size() - 1 and (s[i] == s[i + 1] or s[i] == mp[s[i + 1]])) {
            cnt[s[i]]++;
            i++;
            fl = true;
        }
        cnt[s[i]]++;
        int mx = LLONG_MAX;
        for (auto x: cnt)
            mx = min(mx, x.second);
        if (mp.size() > 1)
            ans += mx;
    }
    cout << ans << endl;
}

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
//    cin >> t;

    while (t--)
        solve();
    return 0;
}


#pragma GCC optimize("O3")
#pragma GCC target("sse4")
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define MAX 1000005
#define M_p 3.1415926
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define fastio ios::sync_with_stdio(0);cin.tie(0);
#define test int t;cin>>t;while(t--)
#define forr(i,x,y) for(int i=x;i<y;i++)
#define all(vect) vect.begin(),vect.end()
#define ull unsigned long long
#define fout fflush(stdout);
#define min3(x,y,z) min(min(x,y),z)
#define min4(x,y,z,w) min(min3(x,y,z),w)
#define endl "\n"
#define N 100005
#define inf 1e17
//#define size 1000000
//	memset(a,0,sizeof(a));
int32_t main()
{
	fastio
	string s;
	cin>>s;
	int k;
	cin>>k;
	set<string> se;
	forr(i,0,k)
	{
		string t;
		cin>>t;
		string t1 = "";
		t1 = t[1]+t[0];
		se.insert(t);
		se.insert(t1);
	}
	int ans = 0;
	int n = s.length();
	forr(i,1,n)
	{
		//cout<<"i = "<<i<<endl;
		string tmp = "";
		tmp=s[i]+s[i-1];
		if(se.find(tmp)!=se.end())
		{
			if(i<n-1 && s[i-1]==s[i+1])
			{
				i++;
			//	cout<<" ="<<i<<endl;
			}
			ans++;
		}
	}
	cout<<ans<<endl;
	return 0;
}


#pragma GCC optimize("O3")
#pragma GCC target("sse4")
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define MAX 1000005
#define M_p 3.1415926
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define fastio ios::sync_with_stdio(0);cin.tie(0);
#define test int t;cin>>t;while(t--)
#define forr(i,x,y) for(int i=x;i<y;i++)
#define all(vect) vect.begin(),vect.end()
#define ull unsigned long long
#define fout fflush(stdout);
#define min3(x,y,z) min(min(x,y),z)
#define min4(x,y,z,w) min(min3(x,y,z),w)
#define endl "\n"
#define N 100005
#define inf 1e17
#define int long long
//#define size 1000000
//	memset(a,0,sizeof(a));
int32_t main()
{
	fastio
	string s;
	cin>>s;
	int k;
	cin>>k;
	map<char,char> m;
	forr(i,0,k)
	{
		char c1,c2;
		cin>>c1>>c2;
		m[c1]=c2;
		m[c2]=c1;
	}
	int retain=0;
	int n = s.length();
	int i=0;
	while(i<n)
	{
		map<char,int> cnt;
		while(i<n-1 && ((s[i]==s[i+1]) || (m[s[i]]==s[i+1])))
		{
			cnt[s[i]]++;
			i++;
		}
		cnt[s[i]]++;
		int mx = 0;
		for(auto it:cnt)
			mx = max(mx,it.second);
		retain += mx;
		i++;
	}
	cout<<n-retain<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define fast { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define pb(x) push_back(x)
#define ll long long

#define vi vector<int>
#define vl vector<long>
#define vll vector<long long>

#define infi INT_MAX
#define infl LONG_MAX
const int inf = 1e17 + 7;
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fi(i,a,b) for(ll i=(b-1);i>=a;i--)
#define F first
#define S second
#define G(a,b) get<a>(b)
#define MP make_pair
#define MT make_tuple
#define ld long double
#define test(t) ll t;cin>>t;while(t--)
string s;

void func()
{
    string s;
    cin>>s;
    ll n,a=0,b=0,ans=0;
    cin>>n;
    for(int i=0;i<n;i++){
        string s2;
        cin>>s2;
        for(int j=0;j<s.length();j++){
            if(s[i]==s2[0]){
                a++;
            }
            else if(s[i]==s2[1]){
                b++;
            }
            else{
                ans+=min(a,b);
            }
        }
        ans+=min(a,b);
        cout<<ans<<"\n";
    }
}

int main()
{
    fast
    //freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);

    //test(t)
    {
      func();
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define fast { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define pb(x) push_back(x)
#define ll long long

#define vi vector<int>
#define vl vector<long>
#define vll vector<long long>

#define infi INT_MAX
#define infl LONG_MAX
const int inf = 1e17 + 7;
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fi(i,a,b) for(ll i=(b-1);i>=a;i--)
#define F first
#define S second
#define G(a,b) get<a>(b)
#define MP make_pair
#define MT make_tuple
#define ld long double
#define test(t) ll t;cin>>t;while(t--)
string s;

void func()
{
    string s;
    cin>>s;
    ll n,a=0,b=0,ans=0;
    cin>>n;
    for(int i=0;i<n;i++){
        string s2;
        cin>>s2;
        a=0;b=0;
        for(int j=0;j<s.length();j++){
            if(s[j]==s2[0]){
                a++;
            }
            else if(s[j]==s2[1]){
                b++;
            }
            else{
                ans+=min(a,b);
                a=0;b=0;
            }
        }
        ans+=min(a,b);

    }
    cout<<ans<<"\n";
}

int main()
{
    fast
    //freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);

    //test(t)
    {
      func();
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define fast { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define pb(x) push_back(x)
#define ll long long

#define vi vector<int>
#define vl vector<long>
#define vll vector<long long>

#define infi INT_MAX
#define infl LONG_MAX
const int inf = 1e17 + 7;
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fi(i,a,b) for(ll i=(b-1);i>=a;i--)
#define F first
#define S second
#define G(a,b) get<a>(b)
#define MP make_pair
#define MT make_tuple
#define ld long double
#define test(t) ll t;cin>>t;while(t--)
string s;

void func()
{
    string s;
    cin>>s;
    ll n,a=0,b=0,ans=0;
    cin>>n;
    for(int i=0;i<n;i++){
        string s2;
        cin>>s2;
        a=0;b=0;
        for(int j=0;j<s.length();j++){
            if(s[j]==s2[0]){
                a++;
            }
            else if(s[j]==s2[1]){
                b++;
            }
            else{
                ans+=min(a,b);
                a=0;b=0;
            }
        }
        ans+=min(a,b);
        cout<<ans<<"\n";
    }
}

int main()
{
    fast
    //freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);

    //test(t)
    {
      func();
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
const long long M = 1e8 ;
int main()
{
    string s;
    cin>>s;
    ll p,n,con=0,k,a=0,b=0;
    n=s.length();
    char x,y;
    vector< pair < char,char>> pr;
    cin>>p;
    for(int i=0;i<p;i++){
        cin>>x>>y;
        pr.pb({x,y});
    }
    for(int i=0;i<p;i++){
            x= pr[i].first;
            y= pr[i].second;
        for(int j=0;j<n;j++){
            if(s[j]==x || s[j]== y){
                    a=0;b=0;
                    for(k=j;k<n;k++){
                        if(s[k]==x)a++;
                        else if(s[k]==y)b++;
                            else
                            break;
                    }
                    con=( min(a,b) ) + con;
                    j=k;
            }

          if(k==n)break;
        }
    }
    cout<<con<<"\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
const long long M = 1e8 ;
int main()
{
    string s;
    cin>>s;
    ll p,n,con=0,k,a=0,b=0;
    n=s.length();
    char x,y;
    vector< pair < char,char>> pr;
    cin>>p;
    for(int i=0;i<p;i++){
        cin>>x>>y;
        pr.pb({x,y});
    }
    for(int i=0;i<p;i++){
            x= pr[i].first;
            y= pr[i].second;
        for(int j=0;j<n;j++){
            if(s[j]==x || s[j]== y){
                    a=0;b=0;
                    for(k=j;k<n;k++){
                        if(s[k]==x)a++;
                        else if(s[k]==y)b++;
                            else
                            break;
                    }
                    con=( min(a,b) ) + con;
                    j=k-1;
                    if(k==n)break;
            }
         // cout<<con<<endl;

        }
    }
    cout<<con<<"\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
const long long M = 1e8 ;
int main()
{
    string s;
    cin>>s;
    ll p,n,con=0;
    n=s.length();
    char x,y;
    vector< pair < char,char>> pr;
    cin>>p;
    for(int i=0;i<p;i++){
        cin>>x>>y;
        pr.pb({x,y});
    }
    for(int i=0;i<p;i++){
            x= pr[i].first;
            y= pr[i].second;
        for(int j=0;j<n-1;j++){
            if((s[j]==x && s[j+1]==y) || (s[j]== y && s[j+1]== x)){
                con++;j++;
            }
        }
    }
    cout<<con<<"\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for (int i = 0; i < n; ++i)
#define REP(i,k,n) for (int i = k; i <= n; ++i)
#define REPR(i,k,n) for (int i = k; i >= n; --i)
#define pb push_back
#define F first
#define S second
#define I insert
#define sz(a) (int)((a).size())
#define all(a) (a).begin(), (a).end()
#define debug1(a) cout<<" "<<#a<<" : "<<a<<"\n"
#define debug2(a,b) cout<<" "<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<"\n"
#define debug3(a,b,c) cout<<" "<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<"\n"
#define debug4(a,b,c,d) cout<<" "<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<"\n"
#define INF (int)10000000000000000
#define PI (double)3.14159265358979
// #define M 421412341324321
#define MOD 1000000007

signed main()
{
	ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);

	string s;
	cin>>s;
	int k;
	cin>>k;
	map < pair <char, char>, int> mp;
	map <char, int> check;
	for (int i = 0 ; i < k ; ++i)
	{
		char x,y;
		cin>>x>>y;
		mp[{x,y}] = 1;
		mp[{y,x}] = 1;
		check[x] = 1;
		check[y] = 1;
	}
	int cnt = 0;
	for (int i = 0 ; i < s.size() ; ++i)
	{
		map <char, int> c;
		c[s[i]]++;
		while(i<s.size() && (mp[{s[i], s[i+1]}] || s[i]==s[i+1]))
		{
			c[s[i+1]]++;
			i++;
		}
		int mx = 0;
		for (auto j:c)
		{
			mx = max(mx,j.S);
		}
		cnt+=mx;
		// debug3(i,s[i],cnt);
	}
	cout<<sz(s)-cnt;

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for (int i = 0; i < n; ++i)
#define REP(i,k,n) for (int i = k; i <= n; ++i)
#define REPR(i,k,n) for (int i = k; i >= n; --i)
#define pb push_back
#define F first
#define S second
#define I insert
#define sz(a) (int)((a).size())
#define all(a) (a).begin(), (a).end()
#define debug1(a) cout<<" "<<#a<<" : "<<a<<"\n"
#define debug2(a,b) cout<<" "<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<"\n"
#define debug3(a,b,c) cout<<" "<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<"\n"
#define debug4(a,b,c,d) cout<<" "<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<"\n"
#define INF (int)10000000000000000
#define PI (double)3.14159265358979
// #define M 421412341324321
#define MOD 1000000007

signed main()
{
	ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);

	string s;
	cin>>s;
	int k;
	cin>>k;
	map < pair <char, char>, int> mp;
	for (int i = 0 ; i < k ; ++i)
	{
		char x,y;
		cin>>x>>y;
		mp[{x,y}] = 1;
		mp[{y,x}] = 1;
	}
	int cnt = 0;
	for (int i = 0 ; i < s.size()-1 ; ++i)
	{
		if (mp[{s[i],s[i+1]}])
		{
			if (i==s.size()-2) cnt++;
			else
			{
				if (mp[{s[i+1],s[i+2]}]) i++;
				cnt++;
			}
			i++;
		}
	}
	cout<<cnt;

	return 0;
}


//In the name of Allah
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace std;
using namespace __gnu_pbds;
using ll = long long;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
#define IO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)

const int N = (int) 2e5 + 5;
char ss[N];

int main() {
    scanf("%s", ss);
    string s = string(ss);
    int n; scanf("%d", &n);
    int arr[26];
    memset(arr, -1, sizeof arr);
    while(n--) {
        char a, b;
        scanf(" %c %c", &a, &b);
        arr[a - 'a'] = b - 'a';
        arr[b - 'a'] = a - 'a';
    }
    int ans = 0;
    for(int i = 0; i < (int) s.size(); i++) {
        if(arr[s[i] - 'a'] == s[i + 1] - 'a') {
            ans++;
            i++;
        }
    }
    printf("%d", ans);
    return 0;
}


//In the name of Allah
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace std;
using namespace __gnu_pbds;
using ll = long long;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
#define IO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)

const int N = (int) 2e5 + 5;
char ss[N];

int main() {
    scanf("%s", ss);
    string s = string(ss);
    int n; scanf("%d", &n);
    int arr[26];
    memset(arr, -1, sizeof arr);
    while(n--) {
        char a, b;
        scanf(" %c %c", &a, &b);
        arr[a - 'a'] = b - 'a';
        arr[b - 'a'] = a - 'a';
    }
    int ans = 0;
    for(int i = 0; i < (int) s.size(); ) {
        int j = i, t1 = 0, t2 = 0;
        int curr = s[i] - 'a', opp = arr[curr];
        while(j < (int) s.size()) {
            int x = s[j] - 'a';
            if(x == curr)
                t1++;
            else if(x == opp)
                t2++;
            else
                break;
            j++;
        }
        ans += min(t1, t2);
        i = j;
    }
    printf("%d", ans);
    return 0;
}


/*
   Author : BabaYaga42,
   BITS Pilani, Hyderabad.
   Don't give up ;)
   */
#include<bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(false);cin.tie(nullptr);

int32_t main()
{
	IOS;
	int k;
	string s;
	map<char,int> mp;
	cin >> s >> k;
	int n = s.size();
	for(int i = 0; i <k;i++)
	{
		string a;
		cin >> a;
		mp[a[0]] = i+1;
		mp[a[1]] = i+1;
	}
	int i = 0,j=0;
	long long ans = 0;
	while(i < n)
	{
		j = i;
		int cnt = 1,c1=0,c2=0;
		set<char> st;
		while(i+1 < n  and mp[s[i]] == mp[s[i+1]])
		{
			cnt++;
			st.insert(s[i]);
			st.insert(s[i+1]);
			i++;
		}
		if(st.size() <= 1)
		{
			i++;
		}
		else
		{
			char ch1,ch2;
			auto it = s.begin();
			ch1 = *(st.begin());
			advance(it,1);
			ch2 = *it;
			while(cnt--)
			{
				if(s[j] == ch1)c1++;
				else c2++;
				j++;
			}
			ans += min(c1,c2);
					//cout << i <<" "<<c1 <<" "<<c2 << endl;
			i++;
		}
	}
	cout << ans;
	return 0;
}


/*
   Author : BabaYaga42,
   BITS Pilani, Hyderabad.
   Don't give up ;)
   */
#include<bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(false);cin.tie(nullptr);

int32_t main()
{
	IOS;
	int k;
	string s;
	map<char,int> mp;
	cin >> s >> k;
	int n = s.size();
	for(int i = 0; i <k;i++)
	{
		string a;
		cin >> a;
		mp[a[0]] = i+1;
		mp[a[1]] = i+1;
	}
	int i = 0,j=0;
	long long ans = 0;
	while(i < n)
	{
		j = i;
		int cnt = 1,c1=0,c2=0;
		set<char> st;
		while(i+1 < n  and mp[s[i]] == mp[s[i+1]])
		{
			cnt++;
			st.insert(s[i]);
			st.insert(s[i+1]);
			i++;
		}
		if(cnt == 1)
		{
			i++;
			continue;
		}
		else if(st.size() == 1)
		{
			ans += i-j+1;
			i++;
		}
		else if(st.size() == 2)
		{
			char ch1,ch2;
			auto it = s.begin();
			ch1 = *(st.begin());
			advance(it,1);
			ch2 = *it;
			while(cnt--)
			{
				if(s[j] == ch1)c1++;
				if(s[j] == ch2)c2++;
				j++;
			}
			ans += min(c1,c2);
			i++;
		}
		else
		{
			assert(1);
		}
	}
	cout << ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

int k;
string s;
map<char, char> m;

int32_t main()
{
	IOS;
	cin>>s>>k;
	for(int i=1;i<=k;i++)
	{
		char ch1, ch2;
		cin>>ch1>>ch2;
		m[ch1]=ch2;
		m[ch2]=ch1;
	}
	int retain=0;
	for(int i=0;i<s.size();i++)
	{
		map<char, int> cnt;
		while(i<s.size()-1 && ((s[i+1]==s[i]) ||(s[i+1]==m[s[i]])))
		{
			cnt[s[i]]++;
			i++;
		}
		cnt[s[i]]++;
		int max1=0;
		for(auto it:cnt)
			max1=max(max1, it.second);
		retain+=max1;
	}
	cout<<s.size()-retain<<endl;
	return 0;
}


/*
   Author : BabaYaga42,
   BITS Pilani, Hyderabad.
   Don't give up ;)
   */
#include<bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(false);cin.tie(nullptr);

int32_t main()
{
	IOS;
	int k;
	string s;
	map<char,int> mp;
	cin >> s >> k;
	int n = s.size();
	for(int i = 0; i <k;i++)
	{
		string a;
		cin >> a;
		mp[a[0]] = i+1;
		mp[a[1]] = i+1;
	}
	int i = 0,j=0;
	long long ans = 0;
	while(i < n)
	{
		j = i;
		int cnt = 1,c1=0,c2=0;
		set<char> st;
		while(i+1 < n  and mp[s[i]] == mp[s[i+1]])
		{
			cnt++;
			st.insert(s[i]);
			st.insert(s[i+1]);
			i++;
		}
		if(cnt == 1)
		{
			i++;
			continue;
		}
		else if(st.size() == 1)
		{
			i++;
		}
		else if(st.size() == 2)
		{
			char ch1,ch2;
			auto it = s.begin();
			ch1 = *(st.begin());
			advance(it,1);
			ch2 = *it;
			while(cnt--)
			{
				if(s[j] == ch1)c1++;
				if(s[j] == ch2)c2++;
				j++;
			}
			ans += min(c1,c2);
			i++;
		}
		else
		{
			assert(1);
		}
	}
	cout << ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define ppb pop_back()
#define ppf pop_front()
#define all(vec) vec.begin(), vec.end()
#define fol(i,a,b) for(int i=a;i<b;i++)
#define loop(i,a,b) for(int i=a;i>=b;i--)
#define forr(x,arr) for(auto& x:arr)
#define mod 1000000007
#define INF 0x3f3f3f3f3f3f3f3f
#define EPS 1e-7
#define sz(x) ((lli)(x).size())
#define endl '\n'

#ifdef SANJU
    #define localsys 1
#else
    #define localsys 0
#endif

using   lli     =   long long;
using   lld     =   long double;
using   ulli    =   unsigned long long int;
using   pll     =   pair<lli, lli>;
using   ttt     =   pair<lli, pll>;
using   vttt    =   vector<ttt>;
using   vll     =   vector<pll>;
using   vl      =   vector<lli>;
using   vi      =   vector<int>;
using   vvi     =   vector<vector<int>>;
using   cd      =   complex<lld>;

int cnvrt(char a,char b)
{
    return (a-'a')*10+(b-'b');
}

void answer(string s,map<int,int>hash)
{
    long long int ans=0;
    map<int,int>fr;

    for(int i=1;i<s.length();i++)
    {
        if(fr.find(i)!=fr.end())continue;

        if(i==1)
        {
            char aa=s[i];
            char bb=s[i-1];
            int a=cnvrt(aa,bb);
            int b=(bb,aa);
            if(hash.find(a)!=hash.end()||hash.find(b)!=hash.end())
            {
                cout<<endl<<a<<endl;
                int temp=cnvrt(s[i-1],s[i+1]);
                if(hash.find(temp)==hash.end())
                {
                    fr[i]=1;
                    i++;
                }
                else fr[i-1]=1;
            }
            continue;
        }

        if(i==s.length()-1)
        {

            int a=cnvrt(s[i],s[i-1]);
            int b=cnvrt(s[i-1],s[i]);
            if(hash.find(a)!=hash.end()||hash.find(b)!=hash.end()){cout<<endl<<a<<endl;fr[i]=1;}
            continue;
        }

            int a=cnvrt(s[i],s[i-1]);
            int b=cnvrt(s[i-1],s[i]);
            if(hash.find(a)!=hash.end()||hash.find(b)!=hash.end())
            {
                cout<<endl<<a<<endl;
                int tempa=cnvrt(s[i-2],s[i]);
                if(hash.find(tempa)==hash.end())
                {
                    fr[i-1]=1;
                    continue;
                }
                else fr[i]=1;
            }

    }

    cout<<fr.size();
}

void sanjeev(int kkkk)
{
    string s;
    cin>>s;

    int n;
    cin>>n;
    map<int,int>hash;
    for(int i=0;i<n;i++)
    {
        char a,b;
        cin>>a>>b;
        int ta=cnvrt(a,b);
        int tb=cnvrt(b,a);
        hash[ta]=1;
        hash[tb]=1;
    }
    answer(s,hash);
}

int main()
{
    if(!localsys) ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    cout << fixed << setprecision(10);
    int t=1;
    //cin>>t;
    fol(i,0,t) { sanjeev(i+1); }
    if(localsys) system("pause");
}


#include <bits/stdc++.h>
using namespace std;

#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define ppb pop_back()
#define ppf pop_front()
#define all(vec) vec.begin(), vec.end()
#define fol(i,a,b) for(int i=a;i<b;i++)
#define loop(i,a,b) for(int i=a;i>=b;i--)
#define forr(x,arr) for(auto& x:arr)
#define mod 1000000007
#define INF 0x3f3f3f3f3f3f3f3f
#define EPS 1e-7
#define sz(x) ((lli)(x).size())
#define endl '\n'

#ifdef SANJU
    #define localsys 1
#else
    #define localsys 0
#endif

using   lli     =   long long;
using   lld     =   long double;
using   ulli    =   unsigned long long int;
using   pll     =   pair<lli, lli>;
using   ttt     =   pair<lli, pll>;
using   vttt    =   vector<ttt>;
using   vll     =   vector<pll>;
using   vl      =   vector<lli>;
using   vi      =   vector<int>;
using   vvi     =   vector<vector<int>>;
using   cd      =   complex<lld>;

void answer(string s,vector<pair<char,char>>A)
{
    long long int ans=0;
    for(int i=0;i<A.size();i++)
    {
        char a=A[i].first;
        char b=A[i].second;

        long long int ca=0;
        long long int cb=0;

        for(int j=0;j<s.length();j++)
        {
            if(s[j]==a)ca++;
            else if(s[j]==b)cb++;
            else
            {
                ans+=min(ca,cb);
                // cout<<endl<<" ans "<<ans<<endl;
                ca=0;
                cb=0;
            }
        }
        ans+=min(ca,cb);
    }
    cout<<ans;

}

void sanjeev(int kkkk)
{
    string s;
    cin>>s;
    int n;
    cin>>n;
    vector<pair<char,char>>A;

    for(int i=0;i<n;i++)
    {
    char a,b;
    cin>>a>>b;
    A.push_back(make_pair(a,b));
    }
    answer(s,A);
}

int main()
{
    if(!localsys) ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    cout << fixed << setprecision(10);
    int t=1;
    //cin>>t;
    fol(i,0,t) { sanjeev(i+1); }
    if(localsys) system("pause");
}


#include <bits/stdc++.h>
using namespace std;

#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define ppb pop_back()
#define ppf pop_front()
#define all(vec) vec.begin(), vec.end()
#define fol(i,a,b) for(int i=a;i<b;i++)
#define loop(i,a,b) for(int i=a;i>=b;i--)
#define forr(x,arr) for(auto& x:arr)
#define mod 1000000007
#define INF 0x3f3f3f3f3f3f3f3f
#define EPS 1e-7
#define sz(x) ((lli)(x).size())
#define endl '\n'

#ifdef SANJU
    #define localsys 1
#else
    #define localsys 0
#endif

using   lli     =   long long;
using   lld     =   long double;
using   ulli    =   unsigned long long int;
using   pll     =   pair<lli, lli>;
using   ttt     =   pair<lli, pll>;
using   vttt    =   vector<ttt>;
using   vll     =   vector<pll>;
using   vl      =   vector<lli>;
using   vi      =   vector<int>;
using   vvi     =   vector<vector<int>>;
using   cd      =   complex<lld>;

void answer(string s,vector<pair<char,char>>A)
{
    long long int ans=0;
    for(int i=0;i<A.size();i++)
    {
        char a=A[i].first;
        char b=A[i].second;

        long long int ca=0;
        long long int cb=0;

        for(int j=0;j<s.length();j++)
        {
            if(s[j]==a)ca++;
            if(s[j]==b)cb++;
            else
            {
                ans+=min(ca,cb);
                ca=0;
                cb=0;
            }
        }
        ans+=min(ca,cb);
    }
    cout<<ans;

}

void sanjeev(int kkkk)
{
    string s;
    cin>>s;
    int n;
    cin>>n;
    vector<pair<char,char>>A;

    for(int i=0;i<n;i++)
    {
    char a,b;
    cin>>a>>b;
    A.push_back(make_pair(a,b));
    }
    answer(s,A);
}

int main()
{
    if(!localsys) ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    cout << fixed << setprecision(10);
    int t=1;
    //cin>>t;
    fol(i,0,t) { sanjeev(i+1); }
    if(localsys) system("pause");
}


#include <bits/stdc++.h>

using namespace std;

char other[128];

int main() {
	string s; cin >> s;
	int n; cin >> n;
	char curr = 0;
	int ans = 0, c1 = 0, c2 = 0;
	for (int i = 0; i < n; i++) {
		string tmp; cin >> tmp;
		other[tmp[0]] = tmp[1];
		other[tmp[1]] = tmp[0];
	}
	s += '.';
	for (int i = 0; i < s.size() + 1; i++) {
		if (!other[s[i]]) {
			curr = 0;
			ans += min(c1, c2);
			c1 = 0;
			c2 = 0;
		}
		else if (other[s[i]] != curr && s[i] != curr) {
			curr = s[i];
			ans += min(c1, c2);
			c1 = 1;
			c2 = 0;
		}
		else {
			if (!curr) curr = s[i];
			if (s[i] == other[curr]) c2++;
			else if (s[i] == curr) c1++;
		}
	}
	cout << ans << endl;
}


#include <bits/stdc++.h>

using namespace std;

char other[128];

int main() {
	string s; cin >> s;
	int n; cin >> n;
	char curr = 0;
	int ans = 0, c1 = 0, c2 = 0;
	for (int i = 0; i < n; i++) {
		string tmp; cin >> tmp;
		other[tmp[0]] = tmp[1];
		other[tmp[1]] = tmp[0];
	}
	for (int i = 0; i < s.size(); i++) {
		if (!other[s[i]]) {
			curr = 0;
			ans += min(c1, c2);
			c1 = 0;
			c2 = 0;
		}
		else if (other[s[i]] != curr && s[i] != curr) {
			curr = s[i];
			ans += min(c1, c2);
			c1 = 1;
			c2 = 0;
		}
		else {
			if (!curr) curr = s[i];
			if (s[i] == other[curr]) c2++;
			else if (s[i] == curr) c1++;
		}
	}
	cout << ans << endl;
}


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

char S[100005],Other[128];
char R[16],state;
int A[100005],B[100005],N,i,j,k,P,c1,c2;
bool bidden;

int main(){
   scanf("%s%d",S+1,&P);
   for (i=1; i<=P; i++){
      scanf("%s",R);
      Other[R[0]] = R[1];
      Other[R[1]] = R[0];
   }
   N = strlen(S+1);
   S[N+1] = '.';
   for (i=1; i<=N+1; i++){
      //printf("%d %d\n",c1,c2);
      if (Other[S[i]]==0){
         state=0;
         k+=min(c1,c2);
         c1=0;
         c2=0;
      } else
      if (Other[S[i]]!=state && S[i]!=state){
         state=S[i];
         k+=min(c1,c2);
         c1=1;
         c2=0;
      } else {
         if (state==0) state=S[i];
         if (S[i]==Other[state]) c2++; else
         if (S[i]==state) c1++;
      }
   }
   printf("%d\n",k);
   return 0;
}


#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define ll long long
#define ii pair<int,int>
ll ara[200005];
ll aa[200004]; ll bb[200004];
int main()
{
    ll a,b,c,d,m,n,i,j,k,l,t,x,y,z;

        ll ans=0;
        ll maxi=0,mini=0,sum=0,mul=1;
        string st;
        string ch;
        cin>>st;
        l=st.length();
        cin>>n;
        for(j=0;j<n;j++)
        {
            cin>>ch;
            for(i=0;i<l-1;i++)
            {
                if((st[i]==ch[0] && st[i+1]==ch[1]) || (st[i]==ch[1] && st[i+1]==ch[0]))
                {
                    ans++;
                    st[i+1]='0';
                }
            }
        }
        cout<<ans<<endl;

    return 0;
}


#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define ll long long
#define ii pair<int,int>
string st;
int main()
{
    ll a,b,c,d,m,n,i,j,k,l,t,x,y,z;

        ll ans=0;
        ll maxi=0,mini=0,sum=0,mul=1;
        string ch;
        cin>>st;
        cin>>k;
        for(i=1;i<=k;i++)
        {
            cin>>ch;
            x=0;y=0;
            for(j=0;st[j];j++)
            {
                if(st[j]==ch[0]) x++;
                else if(st[j]==ch[1]) y++;
                else
                {
                    ans+=min(x,y); x=0,y=0;
                }
            }
            ans+=min(x,y);
        }
        cout<<ans<<endl;

    return 0;
}


#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define ll long long
#define ii pair<int,int>
ll ara[200005];
ll aa[200004]; ll bb[200004];
int main()
{
    ll a,b,c,d,m,n,i,j,k,l,t,x,y,z;

        ll ans=0;
        ll maxi=0,mini=0,sum=0,mul=1;
        string st;
        string ch;
        cin>>st;
        l=st.length();
        cin>>n;
        for(j=0;j<n;j++)
        {
            cin>>ch;
            for(i=0;i<l-1;i++)
            {
                if(st[i]=='0')
                {
                    for(k=i;k<l;k++){
                            st[k]=st[k+1];
                    }
                    l--;
                    i--;
                }
                if((st[i]==ch[0] && st[i+1]==ch[1]) || (st[i]==ch[1] && st[i+1]==ch[0]))
                {
                    ans++;
                    st[i+1]='0';
                }
            }
        }
        cout<<ans<<endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
map<char,char>mp;
int main ()
{
    string s;
    cin>>s;
    int n;
    cin >> n;
    for(int i = 0 ; i < n ; i ++ )
    {
        char a, b;
        cin >> a>> b;
        mp[a]=b;
        mp[b]=a;
    }
    for(int i = 0 ; i < s.size() ; i ++)
    {
        char c= s[i];
        if (mp[c]!=s[i+1])continue;
        int j=i+1 ;
        int cnt1=0;
        int cnt2=0;
        int nexti=i+1;
        while(s[j]==mp[c] && j<s.size())
        {

            cnt1++;
            nexti=j;
            j++;
        }
        j=i;
        while(s[j]==c && j>=0)
        {

            cnt2++;
            j--;
        }

        if (cnt1<cnt2)
        {
            j=i+1;
            while(s[j]==mp[c] && j<s.size())
            {
                s[j]='0';
                j++;
            }
        }
        else
        {
            j=i;
            while(s[j]==c && j>=0)
            {

                s[j]='0';
                j--;
            }
        }
        i=nexti;
    }
    int ans=0;
    for(int i =0 ; i<s.size() ; i++)
        if (s[i]=='0')ans++;
    cout<<ans;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int last[26];
int main ()
{
    string s;
    cin>>s;
    int n;
    cin>>n;
    memset(last,0,sizeof last);
    int ans=0;
    for(int i =0 ; i<n ; i++)
    {
        char a,b;
        cin>>a>>b;
        while(!(s.find(a,last[a-'a'])==string::npos||s.find(b,last[b-'a'])==string::npos))
        {
            int f1=s.find(a,last[a-'a']);
            int f2=s.find(b,last[b-'a']);

            int cnt1=0, cnt2 =0 ;
            for(int j=min(f1,f2) ; j<s.size() ; j++)
            {

                if (s[j]!=a && s[j]!=b)
                {
                    last[a-'a']=j;
                    last[b-'a']=j;

                    break;
                }

                if (s[j]==a)cnt1++;
                if (s[j]==b)cnt2++;

                if (j==s.size()-1)
                {
                    last[a-'a']=-1;
                    last[b-'a']=-1;
                }
            }
            ans+=min(cnt1,cnt2);
            if (last[a-'a']==-1 || last[b-'a']==-1)break;
        }

    }
    cout<<ans;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
map<char,char>mp;
int main ()
{
    string s;
    cin>>s;
    int n;
    cin >> n;
    for(int i = 0 ; i < n ; i ++ )
    {
        char a, b;
        cin >> a>> b;
        mp[a]=b;
        mp[b]=a;
    }
    int ans=0;
    for(int i = 0 ; i < s.size() ; i ++)
    {
        char c= s[i];
        if (mp[c]!=s[i+1])continue;
        int j=i+1 ;
        int cnt1=0;
        int cnt2=0;
        int nexti=i+1;
        while(s[j]==mp[c] && j<s.size())
        {

            cnt1++;
            nexti=j;
            j++;
        }
        j=i;
        while(s[j]==c && j>=0)
        {

            cnt2++;
            j--;
        }

        ans+=min(cnt1,cnt2);
        i=nexti-1;
    }
    for(int i =0 ; i<s.size() ; i++)
        if (s[i]=='0')ans++;
    cout<<ans;

    return 0;
}


// abhishek soni.....[NSIT'22]
#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define letsgo                  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl                    '\n'
#define mp                      make_pair
#define pb                      push_back
#define pf                      push_front
#define pob                     pop_back
#define pof                     pop_front
#define ff                      first
#define ss                      second
#define ALL(x)                  (x).begin(),(x).end()
#define int                     long long
#define ll                      long long
#define deb(x,y)				cout<<x<<" == "<<y<<endl;
#define _deb(x)					cout<<"# "<<x<<endl;
#define set_bits(x)      		__builtin_popcountll(x)
#define unset_bits(x)      		__builtin_ctzll(x)
#define nl(i,a,b,j,m,n)         for(int i=a;i<b;i++)for(int j=m;j<n;j++)
#define fl(i,a,b)               for(int i=a;i<b;i++)
#define bl(i,a,b)               for(int i=a;i>=b;i--)
#define ma(arr,size,type)       type*arr=new type[size]()
#define m2a(arr,row,col,type)   type**arr=new type*[row];fl(i,0,row) arr[i]=new type[col]()
using namespace std;
using namespace __gnu_pbds;
typedef pair<int,int>           pii;
typedef pair<int,pair<int,int>> piii;
typedef vector<vector<int>>     matrix;
/*______________________________________________________________________________________________________________*/
int pow(int a,int b,int m){
    if(a==0)return 0;
    if(b==0)return 1;
    int temp=pow(a,b/2,m);
    temp = ((temp%m)*(temp%m))%m;
    if(b&1) temp = ((temp%m)*(a%m))%m;
    return temp;
}
int string_to_num(string s){
    stringstream num(s); int x; num >> x; return x;
}
string num_to_string(int n){
    string s;
    while(n>0){ s=char(n%10+'0')+s; n/=10; }
    return ((s.length()==0)? "0" : s );
}
/*______________________________________________________________________________________________________________*/

const int mod=1e9+7;
const int R_max=1e2+5;
const int C_max=1e2+5;
/*______________________________________________________________________________________________________________*/

void solve(){
	string s; cin>>s;
	int k; cin>>k;
	int ans = 0;
	int n = s.size() + 1;
	s+='$';
	fl(K,0,k){
		char a,b; cin>>a>>b;
		int cnt1 = 0,cnt2 = 0;
		fl(i,0,n){
			if(s[i] == a) cnt1++;
			else if(s[i] == b) cnt2++;
			else{
				ans += min(cnt2,cnt1);
				cnt2 = 0,cnt1=0;
			}
		}
		// while(i < s.size()){
		// 	int j = i;
		// 	int cnt1 = 0,cnt2 = 0;
		// 	while(s[j] == b || s[j] == a){
		// 		if(s[j]==b)cnt2++;
		// 		else cnt1++;
		// 		j++;
		// 	}
		// 	if(cnt1 != 0 && cnt2 != 0){
		// 		ans += min(cnt2,cnt1);
		// 		i = j;
		// 	}else{
		// 		i++;
		// 	}
		// }
	}
	cout<<ans<<endl;

}

signed main(){
	letsgo
    int t=1;
    // cin>>t;
    for(int T=1;T<=t;T++){
        // cout<<"test case # "<<T<<endl;
        // clock_t z = clock();
        solve();
        // cerr << "Run Time : " << ((double)(clock() - z) / CLOCKS_PER_SEC);
    }
}


// abhishek soni.....[NSIT'22]
#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define letsgo                  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl                    '\n'
#define mp                      make_pair
#define pb                      push_back
#define pf                      push_front
#define pob                     pop_back
#define pof                     pop_front
#define ff                      first
#define ss                      second
#define ALL(x)                  (x).begin(),(x).end()
#define int                     long long
#define ll                      long long
#define deb(x,y)				cout<<x<<" == "<<y<<endl;
#define _deb(x)					cout<<"# "<<x<<endl;
#define set_bits(x)      		__builtin_popcountll(x)
#define unset_bits(x)      		__builtin_ctzll(x)
#define nl(i,a,b,j,m,n)         for(int i=a;i<b;i++)for(int j=m;j<n;j++)
#define fl(i,a,b)               for(int i=a;i<b;i++)
#define bl(i,a,b)               for(int i=a;i>=b;i--)
#define ma(arr,size,type)       type*arr=new type[size]()
#define m2a(arr,row,col,type)   type**arr=new type*[row];fl(i,0,row) arr[i]=new type[col]()
using namespace std;
using namespace __gnu_pbds;
typedef pair<int,int>           pii;
typedef pair<int,pair<int,int>> piii;
typedef vector<vector<int>>     matrix;
/*______________________________________________________________________________________________________________*/
int pow(int a,int b,int m){
    if(a==0)return 0;
    if(b==0)return 1;
    int temp=pow(a,b/2,m);
    temp = ((temp%m)*(temp%m))%m;
    if(b&1) temp = ((temp%m)*(a%m))%m;
    return temp;
}
int string_to_num(string s){
    stringstream num(s); int x; num >> x; return x;
}
string num_to_string(int n){
    string s;
    while(n>0){ s=char(n%10+'0')+s; n/=10; }
    return ((s.length()==0)? "0" : s );
}
/*______________________________________________________________________________________________________________*/

const int mod=1e9+7;
const int R_max=1e2+5;
const int C_max=1e2+5;
/*______________________________________________________________________________________________________________*/

void solve(){
	string s; cin>>s;
	int k; cin>>k;
	int ans = 0;
	fl(K,0,k){
		char a,b; cin>>a>>b;
		int i = 0;
		while(i < s.size()){
			int j = i;
			int cnt1 = 0,cnt2 = 0;
			while(s[j] == b || s[j] == a){
				if(s[j]==b)cnt2++;
				else cnt1++;
				j++;
			}
			if(cnt1 != 0 && cnt2 != 0){
				ans += min(cnt2,cnt1);
				i = j;
			}else{
				i++;
			}
		}
	}
	cout<<ans<<endl;

}

signed main(){
	letsgo
    int t=1;
    // cin>>t;
    for(int T=1;T<=t;T++){
        // cout<<"test case # "<<T<<endl;
        // clock_t z = clock();
        solve();
        // cerr << "Run Time : " << ((double)(clock() - z) / CLOCKS_PER_SEC);
    }
}


// abhishek soni.....[NSIT'22]
#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define letsgo                  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl                    '\n'
#define mp                      make_pair
#define pb                      push_back
#define pf                      push_front
#define pob                     pop_back
#define pof                     pop_front
#define ff                      first
#define ss                      second
#define ALL(x)                  (x).begin(),(x).end()
#define int                     long long
#define ll                      long long
#define deb(x,y)                cout<<x<<" == "<<y<<endl;
#define _deb(x)                    cout<<"# "<<x<<endl;
#define set_bits(x)              __builtin_popcountll(x)
#define unset_bits(x)              __builtin_ctzll(x)
#define nl(i,a,b,j,m,n)         for(int i=a;i<b;i++)for(int j=m;j<n;j++)
#define fl(i,a,b)               for(int i=a;i<b;i++)
#define bl(i,a,b)               for(int i=a;i>=b;i--)
#define ma(arr,size,type)       type*arr=new type[size]()
#define m2a(arr,row,col,type)   type**arr=new type*[row];fl(i,0,row) arr[i]=new type[col]()
using namespace std;
using namespace __gnu_pbds;
typedef pair<int,int>           pii;
typedef pair<int,pair<int,int>> piii;
typedef vector<vector<int>>     matrix;
/*______________________________________________________________________________________________________________*/
int pow(int a,int b,int m){
    if(a==0)return 0;
    if(b==0)return 1;
    int temp=pow(a,b/2,m);
    temp = ((temp%m)*(temp%m))%m;
    if(b&1) temp = ((temp%m)*(a%m))%m;
    return temp;
}
int string_to_num(string s){
    stringstream num(s); int x; num >> x; return x;
}
string num_to_string(int n){
    string s;
    while(n>0){ s=char(n%10+'0')+s; n/=10; }
    return ((s.length()==0)? "0" : s );
}
/*______________________________________________________________________________________________________________*/

const int mod=1e9+7;
const int R_max=1e2+5;
const int C_max=1e2+5;
/*______________________________________________________________________________________________________________*/

void solve(){
    string s; cin>>s;
    int k; cin>>k;
    int ans = s.size();
    fl(K,0,k){
        char a,b; cin>>a>>b;
        int i = 0;
        while(i + 1< s.size()){
            if((s[i] == a && s[i+1] == b )|| (s[i] == b && s[i+1] == a) ){
                int f = i,se = i + 1;
                while(f >= 0 && s[f] == s[i])f--;
                while(i+1 < s.size() && s[se] == s[i+1]) se++;
                if(i - f >= se - i - 1){
                    s = s.substr(0,i + 1) + s.substr(se,s.size() - se);
                    i++;
                }else{
                    s = s.substr(0,f + 1) + s.substr(i+1, s.size() - i - 1);
                    i = f;
                }
            }else{
                i++;
            }
            if(i<0)i = 0;
            // cout<<"I : "<<i<<endl;
            // cout<<s<<endl;
        }
    }
    ans -= s.size();
    cout<<ans<<endl;

}

signed main(){
    letsgo
    int t=1;
    // cin>>t;
    for(int T=1;T<=t;T++){
        // cout<<"test case # "<<T<<endl;
        // clock_t z = clock();
        solve();
        // cerr << "Run Time : " << ((double)(clock() - z) / CLOCKS_PER_SEC);
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 1e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;
string s;
bool vis[N][27];
int dp[N][27];
int pairs[27][27];
int go(int idx,int last){
    if(idx == s.size()){
        return 0;
    }
    if(dp[idx][last]!=-1){
        return dp[idx][last];
    }
        dp[idx][last] = go(idx+1,last)+1;
        if(pairs[s[idx]-'a'][last] == false){
            dp[idx][last] = min(dp[idx][last], go(idx + 1, s[idx] - 'a'));
        }
    return dp[idx][last];
}
void solve()
{
    cin>>s;
    int n;cin>>n;
    mem(dp,-1);
    for(int i=0;i<n;i++){
        string x;cin>>x;
        pairs[x[0]-'a'][x[1]-'a'] = pairs[x[1]-'a'][x[0]-'a'] = true;
    }
    int ans = go(0,26);
    cout<<ans<<endl;
}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 2e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;

void solve()
{
     string s;cin>>s;
     s += '%';
     int n;cin>>n;
     for(int i=0;i<n;i++){
         char a,b;cin>>a>>b;
         int l=0,r=0;
         for(int j=0;j<s.size();j++){
             if(s[j] == a){
                 l++;
             }
             else if(s[j] == b){
                 r++;
             }
             else{
                 res += min(l,r);
                 l=0,r=0;
             }
         }
     }
     cout<<res<<endl;
}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(), x.end()
#define IOS                  \
    ios::sync_with_stdio(0); \
    cin.tie(0);              \
    cout.tie(0);
#define endl "\n"
#define mem(x, y) memset(x, y, sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 1e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9 + 7;
ll res;
string s;
int dp[N][27];
int pairs[27][27];
int go(int idx, int last)
{
    if (idx == s.size())
    {
        return 0;
    }
    if (dp[idx][last] != -1)
    {
        return dp[idx][last];
    }
    dp[idx][last] = go(idx + 1, last) + 1;
    if (pairs[s[idx] - 'a'][last] == false)
    {
        dp[idx][last] = min(dp[idx][last], go(idx + 1, s[idx] - 'a'));
    }
    return dp[idx][last];
}
void solve()
{
    cin >> s;
    int n;
    cin >> n;
    mem(dp, -1);
    for (int i = 0; i < n; i++)
    {
        string x;
        cin >> x;
        pairs[x[0] - 'a'][x[1] - 'a'] = pairs[x[1] - 'a'][x[0] - 'a'] = true;
    }
    int ans = go(0, 0);
    cout << ans << endl;
}

int main()
{
    IOS;
    ll t = 1;
    // cin>>t;
    for (int i = 1; i <= t; i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 2e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;

void solve()
{
     string s;cin>>s;
     int n;cin>>n;
     vector<string> v;
     for(int i=0;i<n;i++){
         string ip;cin>>ip;
         v.pb(ip);
         reverse(all(ip));
         v.pb(ip);
     }
     //cout<<v[0]<<" "<<v[1]<<endl;
     string  p = s;
     for(int i=1;i<s.size();i++){
         string now = "";
         int ptr = i-1;
         bool ff = false;
         while(ptr >= 0){
             if(s[ptr]!='$'){
                 ff = true;
                 now += s[ptr];
                 break;
             }
             ptr--;
         }
         if(ff == false){
             now += s[i];
             now += s[i+1];
             i++;
         }
         else{
             now += s[i];
         }
         bool flag = false;
         for(int j=0;j<v.size();j++){
             if(v[j] == now){
                 flag = true;
                 break;
             }
         }
         if(flag){
             res += 1;
             s[i] = '$';
         }
         else{
             continue;
         }
     }
     int ans1 = res;
     res = 0;
     for(int i=1;i<p.size();i++){
         string now = "";
         int ptr = i-1;
         bool ff = false;
         while(ptr >= 0){
             if(p[ptr]!='$'){
                 ff = true;
                 now += p[ptr];
                 break;
             }
             ptr--;
         }
         if(ff == false){
             now += p[i];
             now += p[i+1];
             i++;
         }
         else{
             now += p[i];
         }
         bool flag = false;
         for(int j=0;j<v.size();j++){
             if(v[j] == now){
                 flag = true;
                 break;
             }
         }
         if(flag){
             res += 1;
             p[i-1] = '$';
         }
         else{
             continue;
         }
     }
     cout<<min((ll)ans1,res);

}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 2e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;

void solve()
{
     string s;cin>>s;
     int n;cin>>n;
     for(int i=0;i<n;i++){
         char a,b;cin>>a>>b;
         int l=0,r=0;
         for(int j=0;j<s.size();j++){
             if(s[j] == a){
                 l++;
             }
             else if(s[j] == b){
                 r++;
             }
             else{
                 res += min(l,r);
                 l = r =0;
             }
         }
     }
     cout<<res<<endl;
}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 2e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;

void solve()
{
     string s;cin>>s;
     int n;cin>>n;
     vector<string> v;
     for(int i=0;i<n;i++){
         string ip;cin>>ip;
         v.pb(ip);
         reverse(all(ip));
         v.pb(ip);
     }
     //cout<<v[0]<<" "<<v[1]<<endl;
     for(int i=1;i<s.size();i++){
         string now = "";
         now += s[i-1];now += s[i];
         bool flag = false;
         for(int j=0;j<v.size();j++){
             if(v[j] == now){
                 flag = true;
                 break;
             }
         }
         if(flag){
             res += 1;
             s[i-1] = '$';
         }
         else{
             continue;
         }
     }
     cout<<res<<endl;

}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 2e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;

void solve()
{
     string s;cin>>s;
     int n;cin>>n;
     vector<string> v;
     for(int i=0;i<n;i++){
         string ip;cin>>ip;
         v.pb(ip);
         reverse(all(ip));
         v.pb(ip);
     }
     //cout<<v[0]<<" "<<v[1]<<endl;
     for(int i=1;i<s.size();i++){
         string now = "";
         now += s[i-1];now += s[i];
         bool flag = false;
         for(int j=0;j<v.size();j++){
             if(v[j] == now){
                 flag = true;
                 break;
             }
         }
         if(flag){
             res += 1;
             s[i] = '$';
         }
         else{
             continue;
         }
     }
     cout<<res<<endl;

}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


//What comes fast doesn't last and What comes last will never be your past :)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
const int N = 1e5 + 5;
const ll inf = 9e18 + 9;
const int mod = 1e9+7;
ll res;
string s;
bool vis[N][27];
int dp[N][27];
int pairs[27][27];
int go(int idx,int last){
    if(idx == s.size()){
        return 0;
    }
    if(vis[idx][last] == false){
        vis[idx][last] = true;
        dp[idx][last] = go(idx+1,last)+1;
        if(pairs[s[idx]-'a'][last] == false){
            dp[idx][last] = min(dp[idx][last], go(idx + 1, s[idx] - 'a'));
        }
    }
    return dp[idx][last];
}
void solve()
{
    cin>>s;
    int n;cin>>n;
    for(int i=0;i<n;i++){
        string x;cin>>x;
        pairs[x[0]-'a'][x[1]-'a'] = pairs[x[1]-'a'][x[0]-'a'] = true;
    }
    int ans = go(0,26);
    cout<<ans<<endl;
}

int main()
{
    IOS;ll t = 1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        solve();
    }
}


#include <bits/stdc++.h>

using namespace std;

#define pb push_back

int cola, k, b[(int)1e5 + 40], ans;
string s;

int main (){
	cin >> s >> k;
	for(int i = 0; i < k; i++){
		string t;
		cin >> t;
		for(int j = 0; j < s.size(); j++){
			int a = 0, b = 0;
			while(j < s.size() && (s[j] == t[0] || s[j] == t[1])){
				if(s[j] == t[0]) a++;
				else b++;
				j++;
			}
			ans += min(a, b);
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define pb push_back

int cola, k, b[(int)1e5 + 40];
string s;

void go(string ss){
	for (int i = 0; i < s.size() + 20; i++) b[i] = 0;
	string w, e = ss;
	reverse(e.begin(), e.end());
	int col1 = 0, col2 = 0;
	for (int i = 0; i < s.size(); i++){
		if (s[i] == ss[0]) b[i] = 1;
		if (s[i] == ss[1]) b[i] = 2;
	//	cout << b[i];
	}

	int ch1 = 0, ch2 = 0, col = 0;
	for (int i = 0; i < s.size() + 1; i++){
		if (b[i]){
			if (b[i] == 1) ch1 = 1;
			else ch2 = 1;
			col++;
		}
		else{
			if (ch1 + ch2 != 2){
				for (int j = i - 1, id = 0; id < col; id++, j--){
					b[j] = 0;
				}
			}
			ch1 = ch2 = col = 0;
		}
	}
	/*cout << endl;
	for (int i = 0; i < s.size(); i++){
		cout << b[i];
	}*/
	//exit(0);
	for (int i = 0; i < s.size(); i++){
		if (s[i] == ss[0] && b[i]) col1++;
		if (s[i] == ss[1] && b[i]) col2++;
	}
	if (col2 < col1) swap(ss[0], ss[1]);
	for (int i = 0; i < s.size(); i++){
		if (ss[0] != s[i] || !b[i]) w += s[i];
		else{ cola++;}
	}
//	cout << endl << ss[0] << col << endl;
	s = w;
//	cout << s;
}

int main (){
	cin >> s >> k;
	for (int i = 0; i < k; i++){
		string ss;
		cin >> ss;
		go(ss);
		//cout << col << endl;
	}
	cout << cola << endl;
	//cout << s;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define pb push_back

int col, k;
string s;

void go(string ss){
	string w, e;
	e = ss;
	reverse(e.begin(), e.end());
	for (int i = 1; i < s.size(); i++){
		if (!(s.substr(i - 1, 2) == ss || s.substr(i - 1, 2) == e)){
			w.pb(s[i]);
		}
		else{
			int id = i;
			string q;
			q += s[id - 1];
			q += s[i];
			while(q == e || q == ss){
				i++;
				if (i == s.size())break;
				q = "";
				q += s[id - 1];
				q += s[i];
				col++;
			}
		}
	}
	s = w;
}

int main (){
	cin >> s >> k;
	for (int i = 0; i < k; i++){
		string ss;
		cin >> ss;
		go(ss);
	}
	cout << col;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define pb push_back

int col, k;
string s;

void go(string ss){
	string w, e;
	e = ss;
	reverse(e.begin(), e.end());
	for (int i = 1; i < s.size(); i++){
		if (!(s.substr(i - 1, 2) == ss || s.substr(i - 1, 2) == e)){
			w.pb(s[i]);
		}
		else col++, i++;
	}
	s = w;
}

int main (){
	cin >> s >> k;
	for (int i = 0; i < k; i++){
		string ss;
		cin >> ss;
		go(ss);
	}
	cout << col;
	return 0;
}


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

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new PrintStream(System.out));
        int n=Integer.parseInt(f.readLine());
        Arrays.fill(size0,1);
        Arrays.fill(size1,1);
        for(int i=0;i<n;i++){
            graph[i]=new ArrayList<>();
            par1[i]=i;
            par0[i]=i;
        }
        for(int i=0;i<n-1;i++){
            StringTokenizer st=new StringTokenizer(f.readLine());
            int a= Integer.parseInt(st.nextToken())-1;
            int b=Integer.parseInt(st.nextToken())-1;
            int c=Integer.parseInt(st.nextToken());
//            graph[a].add(new edge(b,c));
//            graph[b].add(a,c);
            if(c==0) {
                union(a,b,par0,0);
            }
            else {
                union(a,b,par1,1);
            }
        }
        long ans=0;
        boolean found0[]=new boolean[200005];
        boolean found1[]=new boolean[200005];
        for(int i=0;i<n;i++){
            int a=find(i,par0);
            if(!found0[a]){
                ans+=(size0[a]*(size0[a]-1));
                found0[a]=true;
            }
            int b=find(i,par1);
            if(!found1[b]){
                ans+=(size1[b]*(size1[b]-1));
                found1[b]=true;
            }
        }
        for(int i=0;i<n;i++){
            int a=find(i,par0);
            int b=find(i,par1);
            ans+=(size0[a]-1)*(-1+size1[b]);
        }
        System.out.println(ans);
        f.close();
        out.close();
    }
    static void union(int x, int y,int par[],int type){
        x=find(x,par);
        y=find(y,par);

        if(x==y)return;
        //multiply because next vals
        if(type==0){
            size0[x]+=size0[y];
        }
        else{
            size1[x]+=size1[y];
        }
        par[y]=x;
    }
    static int[]par1=new int[220000];
    static int[]par0=new int[220000];
    static long[]size1=new long[220000];
    static long[]size0=new long[220000];
    static int find(int x,int[]par){
        if(x==par[x])return x;
        return par[x]=find(par[x],par);
    }

    static ArrayList<Integer>[]graph=new ArrayList[220000];
}
class edge{
    int to,val;
    edge(int a, int b){
        to=a;val=b;
    }
}


import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
public class Solution{
    static InputReader sc;
    static PrintWriter wc;
    static class Pair{
        int x,y;
        Pair(int x,int y){
            this.x=x;
            this.y=y;
        }
    }
    static long arr[][];
    static ArrayList<Pair> graph[];
    static long res=0;
    static void dfs(int node, int par){
        for(Pair p: graph[node]){
            if(p.x!=par){
                dfs(p.x,node);
                if(p.y==0){
                    arr[node][0]+=arr[p.x][0]+1;
                    arr[node][1]+=arr[p.x][1]+arr[p.x][2]+1;
                }
                else{
                    arr[node][2]+=arr[p.x][2]+1;
                }
            }
        }
        res+=arr[node][1]+arr[node][2];
        for(Pair p: graph[node]){
            if(p.x!=par){
                if(p.y==0){
                    res+=(arr[p.x][0]+1)*(arr[node][1]+arr[node][2]-(arr[p.x][1]+arr[p.x][2]));
                }
                else{
                    res+=(arr[p.x][1]+1+arr[p.x][2])*(arr[node][2]-arr[p.x][2]);
                }
            }
        }
    }
    public static void main(String[] args) {
        sc=new InputReader(System.in);
        wc=new PrintWriter(System.out);
        int n=sc.nextInt();
        graph=new ArrayList[n+1];
        arr=new long[n+1][3];
        int i,a,b,w;
        for(i=0;i<=n;i++){
            graph[i]=new ArrayList<Pair>();
        }
        for(i=0;i<n-1;i++){
            a=sc.nextInt();
            b=sc.nextInt();
            w=sc.nextInt();
            graph[a].add(new Pair(b,w));
            graph[b].add(new Pair(a,w));
        }
        dfs(1,-1);
        wc.println(res);
        wc.close();
    }
    static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine()
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
                return res * sgn;
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
}


import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
public class Solution{
    static InputReader sc;
    static PrintWriter wc;
    static class Pair{
        int x,y;
        Pair(int x,int y){
            this.x=x;
            this.y=y;
        }
    }
    static long arr[][];
    static ArrayList<Pair> graph[];
    static long res=0;
    static void dfs(int node, int par){
        for(Pair p: graph[node]){
            if(p.x!=par){
                dfs(p.x,node);
                if(p.y==0){
                    arr[node][0]+=arr[p.x][0]+1;
                    arr[node][1]+=arr[p.x][1]+arr[p.x][3]+1;
                }
                else{
                    arr[node][2]+=arr[p.x][2]+arr[p.x][0]+1;
                    arr[node][3]+=arr[p.x][3]+1;
                }
            }
        }
        res+=arr[node][0]+arr[node][1]+arr[node][2]+arr[node][3];
        for(Pair p: graph[node]){
            if(p.x!=par){
                if(p.y==0){
                    res+=(arr[p.x][0]+1)*(arr[node][1]+arr[node][3]-arr[p.x][1]-arr[p.x][3]-1);
                }
                else{
                    res+=(arr[p.x][2]+arr[p.x][0]+1)*(arr[node][3]-arr[p.x][3]-1);
                }
            }
        }
    }
    public static void main(String[] args) {
        sc=new InputReader(System.in);
        wc=new PrintWriter(System.out);
        int n=sc.nextInt();
        graph=new ArrayList[n+1];
        arr=new long[n+1][4];
        int i,a,b,w;
        for(i=0;i<=n;i++){
            graph[i]=new ArrayList<Pair>();
        }
        for(i=0;i<n-1;i++){
            a=sc.nextInt();
            b=sc.nextInt();
            w=sc.nextInt();
            graph[a].add(new Pair(b,w));
            graph[b].add(new Pair(a,w));
        }
        dfs(1,-1);
        /*for(i=1;i<=n;i++){
            wc.println(arr[i][0]+" "+arr[i][1]+" "+arr[i][2]+" "+arr[i][3]);
        }*/
        wc.println(res);
        wc.close();
    }
    static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine()
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
                return res * sgn;
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
}


import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
public class Solution{
    static InputReader sc;
    static PrintWriter wc;
    static class Pair{
        int x,y;
        Pair(int x,int y){
            this.x=x;
            this.y=y;
        }
    }
    static long arr[][];
    static ArrayList<Pair> graph[];
    static long res=0;
    static void dfs(int node, int par){
        for(Pair p: graph[node]){
            if(p.x!=par){
                dfs(p.x,node);
                if(p.y==0){
                    arr[node][0]+=arr[p.x][1]+arr[p.x][0]+1;
                }
                else{
                    arr[node][1]+=arr[p.x][1]+1;
                }
            }
        }
        res+=arr[node][0]+arr[node][1];
        for(Pair p: graph[node]){
            if(p.x!=par){
                if(p.y==0){
                    res+=(arr[p.x][0]+1)*(arr[node][0]+arr[node][1]-(arr[p.x][0]+arr[p.x][1]));
                }
                else{
                    res+=(arr[p.x][1]+1+arr[p.x][0])*(arr[node][1]-arr[p.x][1]);
                }
            }
        }
    }
    public static void main(String[] args) {
        sc=new InputReader(System.in);
        wc=new PrintWriter(System.out);
        int n=sc.nextInt();
        graph=new ArrayList[n+1];
        arr=new long[n+1][2];
        int i,a,b,w;
        for(i=0;i<=n;i++){
            graph[i]=new ArrayList<Pair>();
        }
        for(i=0;i<n-1;i++){
            a=sc.nextInt();
            b=sc.nextInt();
            w=sc.nextInt();
            graph[a].add(new Pair(b,w));
            graph[b].add(new Pair(a,w));
        }
        dfs(1,-1);
        wc.println(res);
        wc.close();
    }
    static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine()
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
                return res * sgn;
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

public class ForcesC {

	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;
		//it reads the data about the specified point and divide the data about it ,it is quite fast
		//than using direct

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());//converts string to integer
		}

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

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}

		static class DJSet
		{
		    int[] rank;
		    int[] size;
		    int[] parent;
		    int n;

		    public DJSet(int n)
		    {
		        rank = new int[n];
		        parent = new int[n];
		        size = new int[n];
		        this.n = n;
		        makeSet();
		    }

		    void makeSet()
		    {
		        for (int i=0; i<n; i++)
		        {
		            size[i] = 1;
		            parent[i] = i;
		        }
		    }

		    int find(int x)
		    {

		        if (parent[x]!=x)
		        {
		            parent[x] = find(parent[x]);

		        }

		        return parent[x];
		    }

		    void union(int x, int y)
		    {

		        int xRoot = find(x), yRoot = find(y);

		        if (xRoot == yRoot)
		            return;

		        if (rank[xRoot] < rank[yRoot]) {

		            parent[xRoot] = yRoot;
		            size[yRoot]+=size[xRoot];

		        }else if (rank[yRoot] < rank[xRoot]) {

		            parent[yRoot] = xRoot;
		            size[xRoot]+=size[yRoot];
		        } else
		        {

		            parent[yRoot] = xRoot;
		            size[xRoot]+=size[yRoot];
		            rank[xRoot] = rank[xRoot] + 1;
		        }
		    }
		}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long mod = (long)(1e9+7);
	static FastReader sc = new FastReader();
   // static List<Integer>[] edge ;
	public static void main(String[] args) {
		int n = sc.nextInt();
		List<Integer>[] one = new ArrayList[n+1];
		DJSet dsu = new DJSet(n+1);
		for(int i=0;i<=n;++i) {
			one[i] = new ArrayList<>();
		}
		for(int i=0;i<n-1;++i) {
			int u = sc.nextInt();
			int v = sc.nextInt();
			int c = sc.nextInt();
			if(c == 1) {
				one[u].add(v);
				one[v].add(u);
			}else {
				dsu.union(u, v);
			}
		}
		long ans = 0;

		List<List<Integer>> cmp = getComponents(one,n);
		for(List<Integer> x : cmp) {
			long sz = x.size();
			ans+=(sz-1)*sz;
			for(int i : x) {
				long szz = dsu.size[dsu.find(i)];
				ans+=(szz-1)*sz;

			}
		}
		out.println(ans);
		out.close();

	}

	private static List<List<Integer>> getComponents(List<Integer>[] edges, int n) {
		List<List<Integer>> output = new ArrayList<>();
		boolean[] visited = new boolean[n+1];
		for(int i=1;i<=n;++i) {
			if(!visited[i]) {
				List<Integer> component = new ArrayList<>();
				dfs(edges,component,visited,i);
				output.add(component);
			}
		}
		return output;
	}

	private static void dfs(List<Integer>[] edges, List<Integer> component, boolean[] visited, int v) {

		visited[v] = true;
		component.add(v);
		for(int i=0;i<edges[v].size();++i) {
			int adjV = edges[v].get(i);
			if(!visited[adjV])
				dfs(edges,component,visited,adjV);
		}
	}
}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

public class ForcesC {

	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;
		//it reads the data about the specified point and divide the data about it ,it is quite fast
		//than using direct

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());//converts string to integer
		}

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

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long mod = (long)(1e9+7);
	static FastReader sc = new FastReader();
   // static List<Integer>[] edge ;
	public static void main(String[] args) {
		int n = sc.nextInt();
		List<Integer>[] one = new ArrayList[n+1];
		    int[] parent0 = new int[n+1];
		    int[] size0 = new int[n+1];
		    for(int i=0;i<=n;++i) parent0[i] = i;
		    Arrays.fill(size0,1);
		for(int i=0;i<=n;++i) {
			one[i] = new ArrayList<>();
		}
		for(int i=0;i<n-1;++i) {
			int u = sc.nextInt();
			int v = sc.nextInt();
			int c = sc.nextInt();
			if(c == 1) {
				one[u].add(v);
				one[v].add(u);
			}else {
				go(u,v,parent0,size0);
			}
		}
		long ans = 0;
		List<List<Integer>> cmp = getComponents(one,n);
		for(List<Integer> x : cmp) {

			ans+=(long)((x.size()-1)*x.size());
			for(int i : x) {
				int sz = size0[findParent(i,parent0)];
				ans+=(long)((sz-1)*x.size());

			}
		}
		out.println(ans);
		out.close();

	}
	private static void go(int a, int b, int[] parent, int[] size) {
		int aparent = findParent(a,parent);
    	int bparent = findParent(b,parent);

    	if(aparent != bparent) {
    		size[aparent]+=size[bparent];
    		parent[bparent] = aparent;
    	}
	}

	private static int findParent(int v, int[] parent) {
		if(parent[v] == v) return v;
		else return findParent(parent[v], parent);
	}
	private static List<List<Integer>> getComponents(List<Integer>[] edges, int n) {
		List<List<Integer>> output = new ArrayList<>();
		boolean[] visited = new boolean[n+1];
		for(int i=1;i<=n;++i) {
			if(!visited[i]) {
				List<Integer> component = new ArrayList<>();
				dfs(edges,component,visited,i);
				output.add(component);
			}
		}
		return output;
	}

	private static void dfs(List<Integer>[] edges, List<Integer> component, boolean[] visited, int v) {

		visited[v] = true;
		component.add(v);
		for(int i=0;i<edges[v].size();++i) {
			int adjV = edges[v].get(i);
			if(!visited[adjV])
				dfs(edges,component,visited,adjV);
		}
	}
}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

public class ForcesC {

	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;
		//it reads the data about the specified point and divide the data about it ,it is quite fast
		//than using direct

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());//converts string to integer
		}

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

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}

		static class DJSet
		{
		    int[] rank;
		    int[] size;
		    int[] parent;
		    int n;

		    public DJSet(int n)
		    {
		        rank = new int[n];
		        parent = new int[n];
		        size = new int[n];
		        this.n = n;
		        makeSet();
		    }

		    void makeSet()
		    {
		        for (int i=0; i<n; i++)
		        {
		            size[i] = 1;
		            parent[i] = i;
		        }
		    }

		    int find(int x)
		    {

		        if (parent[x]!=x)
		        {
		            parent[x] = find(parent[x]);

		        }

		        return parent[x];
		    }

		    void union(int x, int y)
		    {

		        int xRoot = find(x), yRoot = find(y);

		        if (xRoot == yRoot)
		            return;

		        if (rank[xRoot] < rank[yRoot]) {

		            parent[xRoot] = yRoot;
		            size[yRoot]+=size[xRoot];

		        }else if (rank[yRoot] < rank[xRoot]) {

		            parent[yRoot] = xRoot;
		            size[xRoot]+=size[yRoot];
		        } else
		        {

		            parent[yRoot] = xRoot;
		            size[xRoot]+=size[yRoot];
		            rank[xRoot] = rank[xRoot] + 1;
		        }
		    }
		}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long mod = (long)(1e9+7);
	static FastReader sc = new FastReader();
   // static List<Integer>[] edge ;
	public static void main(String[] args) {
		int n = sc.nextInt();
		List<Integer>[] one = new ArrayList[n+1];
		DJSet dsu = new DJSet(n+1);
		for(int i=0;i<=n;++i) {
			one[i] = new ArrayList<>();
		}
		for(int i=0;i<n-1;++i) {
			int u = sc.nextInt();
			int v = sc.nextInt();
			int c = sc.nextInt();
			if(c == 1) {
				one[u].add(v);
				one[v].add(u);
			}else {
				dsu.union(u, v);
			}
		}
		long ans = 0;

		List<List<Integer>> cmp = getComponents(one,n);
		for(List<Integer> x : cmp) {

			ans+=(long)((x.size()-1)*x.size());
			for(int i : x) {
				int sz = dsu.size[dsu.find(i)];
				ans+=(long)((sz-1)*x.size());

			}
		}
		out.println(ans);
		out.close();

	}

	private static List<List<Integer>> getComponents(List<Integer>[] edges, int n) {
		List<List<Integer>> output = new ArrayList<>();
		boolean[] visited = new boolean[n+1];
		for(int i=1;i<=n;++i) {
			if(!visited[i]) {
				List<Integer> component = new ArrayList<>();
				dfs(edges,component,visited,i);
				output.add(component);
			}
		}
		return output;
	}

	private static void dfs(List<Integer>[] edges, List<Integer> component, boolean[] visited, int v) {

		visited[v] = true;
		component.add(v);
		for(int i=0;i<edges[v].size();++i) {
			int adjV = edges[v].get(i);
			if(!visited[adjV])
				dfs(edges,component,visited,adjV);
		}
	}
}


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

public class Main {
	static Integer[][] fa = new Integer[2][200001];
	static Integer[][] size = new Integer[2][200001];

	public static int find(int c, int x) {
		if (x == fa[c][x]) return x;
		fa[c][x] = find(c, fa[c][x]);
		return fa[c][x];
	}

	public static void merge(int c, int x, int y) {
		x = find(c, x);
		y = find(c, y);
		if (x==y) return;

		fa[c][x] = y;
		size[c][y] += size[c][x];
	}

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

		int n = in.nextInt();
		for (int i = 1; i <= n; i++) {
			fa[0][i] = fa[1][i] = i;
			size[0][i] = size[1][i] = 1;
		}

		for (int i = 1; i < n; i++) {
			int u = in.nextInt(), v = in.nextInt(), c = in.nextInt();
			merge(c, u, v);
		}

		long ans = 0;
		for (int i = 1; i <= n; i++) {
			if (fa[0][i] == i) ans += 1L * size[0][i] * (size[0][i] - 1);
			if (fa[1][i] == i) ans += 1L * size[1][i] * (size[1][i] - 1);
			ans += 1L * (size[0][find(0, i)] - 1) * (size[1][find(1, i)] - 1);
		}
		System.out.println(ans);
	}
}


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

public class Main {
	static Integer[][] fa = new Integer[2][200001];
	static Integer[][] size = new Integer[2][200001];

	public static int find(int c, int x) {
		if (x == fa[c][x]) return x;
		fa[c][x] = find(c, fa[c][x]);
		return fa[c][x];
	}

	public static void merge(int c, int x, int y) {
		x = find(c, x);
		y = find(c, y);
		if (x == y) return;

		fa[c][x] = y;
		size[c][y] += size[c][x];
	}

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

		int n = in.nextInt();
		for (int i = 1; i <= n; i++) {
			fa[0][i] = fa[1][i] = i;
			size[0][i] = size[1][i] = 1;
		}

		for (int i = 1; i < n; i++) {
			int u = in.nextInt(), v = in.nextInt(), c = in.nextInt();
			merge(c, u, v);
		}

		long ans = 0;
		for (int i = 1; i <= n; i++) {
			if (fa[0][i] == i) ans += 1L * size[0][i] * (size[0][i] - 1);
			if (fa[1][i] == i) ans += 1L * size[1][i] * (size[1][i] - 1);
			ans += 1L * (size[0][find(0, i)] - 1) * (size[1][find(1, i)] - 1);
		}
		System.out.println(ans);
	}
}


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

public class A {

	static ArrayList<edge>[] adj;
	static int []dp,ones;

	static void dfs1(int u,int p) {

		for(edge nxt:adj[u])
		{
			int v=nxt.v,t=nxt.t;
			if(v!=p) {
				dfs1(v,u);
				if(t==1) {
					dp[u]+=1+ones[v];
					ones[u]+=1+ones[v];
				}
				else
					dp[u]+=1+dp[v];
			}

		}
	}
	static long dfs2(int u,int p,int t) {

		if(p!=-1)
		{
			if(t==0)
				dp[u]=dp[p];
			else {
				dp[u]+=ones[p]-(ones[u]);
				ones[u]+=ones[p]-(ones[u]);
			}

		}

		long ans=dp[u];
		for(edge nxt:adj[u])
		{
			int v=nxt.v;
			if(v!=p)
				ans+=dfs2(v,u,nxt.t);
		}
		return ans;

	}
		public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = sc.nextInt();
		adj=new ArrayList[n];
		dp=new int [n];
		ones=new int [n];

		for(int i=0;i<n;i++) {
			adj[i]=new ArrayList();

		}
		for(int i=1;i<n;i++)
		{
			int u=sc.nextInt()-1,v=sc.nextInt()-1,t=sc.nextInt();
			adj[u].add(new edge(v,t));
			adj[v].add(new edge(u,t));
		}
		dfs1(1,-1);

		out.println(dfs2(1,-1,-1));
		out.close();

	}

	static class edge {
		int v, t;

		edge(int a, int b) {
			v = a;
			t = b;
		}
	}

	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		Scanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		Scanner(String fileName) throws FileNotFoundException {
			br = new BufferedReader(new FileReader(fileName));
		}

		String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		String nextLine() throws IOException {
			return br.readLine();
		}

		int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		long nextLong() throws NumberFormatException, IOException {
			return Long.parseLong(next());
		}

		double nextDouble() throws NumberFormatException, IOException {
			return Double.parseDouble(next());
		}

	}

}