#include<iostream>
#include<sstream>
#include<string>
#include<utility>
#include<unordered_set>
#include<unordered_map>
#include<map>
#include<iterator>
#include<vector>
#include<math.h>
#include<algorithm>
#include<chrono>
using namespace std;
using namespace std::chrono;

typedef long long int ll;
typedef vector <long long int> vll;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector <vector<char>> vvc;
typedef vector <vector <int>> vvi;
typedef vector <vector <long long int>> vvl;
typedef pair <int, int> pi;
typedef pair<long long int, long long int> pll;
typedef vector <pair <int, int>> vpi;
typedef vector <pair <long long int, long long int>> vpl;
typedef unordered_set <int> si;
typedef unordered_map <int, int> mi;

#define all(v) v.begin() , v.end()
#define IOS ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
const ll mod = 1e9 + 7;

template <typename Type>
istream& operator >> (istream& in, vector<Type>& v)
{
	ll n = v.size();
	for (int i = 0; i < n; i++)
		in >> v[i];
	return in;
}

template <typename Type>
ostream& operator << (ostream& out, vector<Type>& v)
{
	for (auto value : v)
		out << value << " ";
	out << endl;
	return out;
}
void solve()
{
	ll n, positive = INT_MIN, negetive = INT_MIN, flag = 0, sum = 0, prev = 0;
	cin >> n;
	vll a(n);
	cin >> a;
	a[0] > 0 ? flag = 1 : flag = 0;
	prev = flag;
	for (ll i = 0 ; i < n ; ++i)
	{
		a[i] > 0 ? flag = 1 : flag = 0;
		if (flag == 1)
			positive = max(positive, a[i]);
		else
		    negetive = max(negetive, a[i]);
		if (flag != prev || i == n - 1)
		{
			if (prev == 1)
			{
				sum += positive;
				positive = INT_MIN;
			}
			else
			{
				sum += negetive;
				negetive = INT_MIN;
			}
			if (i == n - 1 && prev != flag)
				sum += a[n - 1];
			prev = flag;
		}
	}
	cout << sum << "\n";
}
int main(void)
{
	IOS
		ll t;
	cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}


#include<iostream>
#include<vector>

using namespace std;

int main(){
	int test_amount;
	cin>>test_amount;
	int testamount=test_amount;
	vector<long long int>ansrec;

	while(testamount--){
		long int test_case;
		cin>>test_case;

		long long int tempnum0;
		cin>>tempnum0;//tempnum0是第一個數字
		long long int max=tempnum0;//max來記錄這一串連續的正數或負數數列的最大值
		long long int prev=tempnum0;//拿來紀錄上一個
		long long int ans=0;
		//vector<long long int>rec;
		for(int i=0;i<test_case-1;i++){
			long long int tempnum=0;
			cin>>tempnum;
			if(prev*tempnum>0){//同號
				if(tempnum>max){
					max=tempnum;
				}
			}
			else if(prev*tempnum<0){
				ans+=max;
				//rec.push_back(max);
				max=tempnum;
			}
			prev=tempnum;
		}
		//rec.push_back(max);
		ans+=max;
		//long long int ans=0;
		/*for(int i=0;i<rec.size();i++){
			ans+=rec[i];
		}*/
		//cout<<ans<<endl;
		ansrec.push_back(ans);
	}
	for(int i=0;i<ansrec.size();i++){
		cout<<ansrec[i]<<endl;
	}

}


#include<iostream>
#include<vector>

using namespace std;

int main(){
	int test_amount;
	cin>>test_amount;
	int testamount=test_amount;
	vector<long long int>ansrec;

	while(testamount--){
		long int test_case;
		cin>>test_case;

		long long int tempnum0;
		cin>>tempnum0;//tempnum0是第一個數字
		long long int max=tempnum0;//max來記錄這一串連續的正數或負數數列的最大值
		long long int prev=tempnum0;//拿來紀錄上一個

		vector<long long int>rec;
		for(int i=0;i<test_case-1;i++){
			long long int tempnum=0;
			cin>>tempnum;
			if(prev*tempnum>0){//同號
				if(tempnum>max){
					max=tempnum;
				}
			}
			else if(prev*tempnum<0){
				rec.push_back(max);
				max=tempnum;
			}
			prev=tempnum;
		}
		rec.push_back(max);
		long long int ans=0;
		for(int i=0;i<rec.size();i++){
			ans+=rec[i];
		}
		//cout<<ans<<endl;
		ansrec.push_back(ans);
	}
	for(int i=0;i<ansrec.size();i++){
		cout<<ansrec[i]<<endl;
	}

}


#include<iostream>
#include<vector>

using namespace std;

int main(){
	int test_amount;
	cin>>test_amount;
	int testamount=test_amount;
	vector<long long int>ansrec;

	while(testamount--){
		long int test_case;
		cin>>test_case;

		long long int tempnum0;
		cin>>tempnum0;//tempnum0是第一個數字
		long long int max=tempnum0;//max來記錄這一串連續的正數或負數數列的最大值
		long long int prev=tempnum0;//拿來紀錄上一個
		long long int ans=0;
		//vector<long long int>rec;
		for(int i=0;i<test_case-1;i++){
			long long int tempnum=0;
			cin>>tempnum;
			if(prev*tempnum>0){//同號
				if(tempnum>max){
					max=tempnum;
				}
			}
			else if(prev*tempnum<0){
				ans+=max;
				//rec.push_back(max);
				max=tempnum;
			}
			prev=tempnum;
		}
		//rec.push_back(max);
		ans+=max;
		long long int ans=0;
		/*for(int i=0;i<rec.size();i++){
			ans+=rec[i];
		}*/
		//cout<<ans<<endl;
		ansrec.push_back(ans);
	}
	for(int i=0;i<ansrec.size();i++){
		cout<<ansrec[i]<<endl;
	}

}


#include<iostream>
#include<vector>

using namespace std;

int main(){
	int test_amount;
	cin>>test_amount;
	int testamount=test_amount;
	vector<long long int>ansrec;

	while(testamount--){
		long int test_case;
		cin>>test_case;

		long long int tempnum0;
		cin>>tempnum0;//tempnum0是第一個數字
		long long int max=tempnum0;//max來記錄這一串連續的正數或負數數列的最大值
		long long int prev=tempnum0;//拿來紀錄上一個

		vector<long long int>rec;
		for(int i=0;i<test_case-1;i++){
			long long int tempnum=0;
			cin>>tempnum;
			if(prev*tempnum>0){//同號
				if(tempnum>max){
					max=tempnum;
				}
			}
			else if(prev*tempnum<0){
				rec.push_back(max);
				max=tempnum;
			}
			prev=tempnum;
		}
		rec.push_back(max);
		long long int ans=0;
		for(int i=0;i<rec.size();i++){
			ans+=rec[i];
		}
		//cout<<ans<<endl;
		ansrec.push_back(ans);
	}
	for(int i=0;i<ansrec.size();i++){
		cout<<ansrec[i]<<endl;
	}

}
//hehe


#include <iostream>
#include <vector>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		bool isPositive = true;
		cin >> n;
		vector<int> vec(n);
		for (int i = 0; i < n; ++i)
			cin >> vec[i];

		if (vec[0] < 0)isPositive = false;
		long long int sum = 0;
		long long int val = vec[0];
		for (int i = 1; i < n; ++i)
		{
			if (vec[i] * vec[i - 1] < 0)
			{
				isPositive = !isPositive;
				sum += val;
				val = -9000000000;
			}
			if (val < vec[i])val = vec[i];
		}
		sum += val;
		cout << sum<<endl;
	}

	return 0;
}


#include <iostream>
#include <vector>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		cin >> n;
		vector<long long int> vec(n);
		for (int i = 0; i < n; ++i)
			cin >> vec[i];

		long long int sum = 0;
		long long int val = vec[0];
		for (int i = 1; i < n; ++i)
		{
			if (vec[i] * vec[i - 1] < 0)
			{
				sum += val;
				val = -9000000000;
			}
			if (val < vec[i])val = vec[i];
		}
		sum += val;
		cout << sum<<endl;
	}

	return 0;
}


#include <iostream>
#include<list>
#include<vector>
#include <algorithm>

using namespace std;

// main() is where program execution begins

void testcase() {
    int l; std::cin >> l;
    vector<long> v(l);
    for (int i = 0; i < l; i++) {
        cin >> v[i];
		//std::cout << v[i] << ' ';
    }

    bool prev = v[0] > 0 ? true : false;
	long long sum = 0LL;
	long max = v[0];
	for (int i = 0; i < l; i++) {
		if (prev) { // last was true
			if (v[i] > 0) { // this also
				max = max > v[i] ? max : v[i];
			}
			else {
				sum += max;

				max = v[i];
				prev = false;
			}
		}
		else {
			if (v[i] < 0) { // this also
				max = max > v[i] ? max : v[i];
			}
			else {
				sum += max;
				max = v[i];
				prev = true;
			}
		}

	}
	sum += max;
	std::cout << sum << '\n';

}

int main() {
	int s; std::cin >> s;
	for (int i = 0; i < s; i++) {
		testcase();
	}

	return 0;
}


//g++  5.4.0

#include <iostream>
using namespace std;
typedef long long int ll;
int main()
{ ll t,n,s,p,c;
 cin>>t;
while (t--){
cin>>n;s=0;
cin>>p;n--;
while (n--){
cin>>c;
if(p*c>0){if(c>p)p=c; }
else  {s+=p;p=c;}
}
cout<<s+p<<endl;
}
return 0;
}


//g++  5.4.0

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{ ll t,n,s,p,c;
 cin>>t;
while (t--){
cin>>n;s=0;
cin>>p;n--;
while (n--){
cin>>c;
if(p*c>0){if(c>p)p=c; }
else  {s+=p;p=c;}
}
cout<<s+p<<endl;
}
return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;

int n, t, arr[202020], now,maxlen,maxplus,maxminus;
long long maxsum;

int main() {
	scanf_s("%d", &t);
	while (t--)
	{
		scanf_s("%d", &n);
		for (int i=0;i<n;i++) {
			scanf_s("%d", &arr[i]);
			if (n==1) maxsum=arr[i];
			if (i==0) {
				if (arr[i]>0) {
					now=1;
					maxplus=arr[i];
				}
				else {
					now=-1;
					maxminus=arr[i];
				}

			}
			else {
				if (now==1&&now*arr[i]<0) {
					now=-1;
					maxminus=arr[i];
					maxsum=maxsum+maxplus;
					maxplus=0;
					if (i==n-1) maxsum=maxsum+maxminus, maxplus=0;
				}
				else if(now==-1&&now*arr[i]<0){
					now=1;
					maxplus=arr[i];
					maxsum=maxsum+maxminus;
					maxminus=0;
					if (i==n-1) maxsum=maxsum+maxplus, maxplus=0;
				}
				else if (now==1&&now*arr[i]>0) {
					maxplus=max(maxplus, arr[i]);
					if (i==n-1) maxsum=maxsum+maxplus, maxplus=0;
				}
				else if (now==-1&&now*arr[i]>0) {
					maxminus=max(maxminus, arr[i]);
					if (i==n-1) maxsum=maxsum+maxminus, maxminus=0;
				}
			}
		}
		cout<<maxsum<<endl;
		maxsum=0;
	}
	return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;

int n, t, arr[202020], now,maxlen,maxplus,maxminus;
long long maxsum;

int main() {
	scanf_s("%d", &t);
	while (t--)
	{
		scanf_s("%d", &n);
		for (int i=0;i<n;i++) {
			scanf_s("%d", &arr[i]);
			if (i==0) {
				if (arr[i]>0) {
					now=1;
					maxplus=arr[i];
				}
				else {
					now=-1;
					maxminus=arr[i];
				}

			}
			else {
				if (now==1&&now*arr[i]<0) {
					now=-1;
					maxminus=arr[i];
					maxsum=maxsum+maxplus;
					maxplus=0;
					maxlen++;
					if (i==n-1) maxsum=maxsum+maxminus, maxplus=0;
				}
				else if(now==-1&&now*arr[i]<0){
					now=1;
					maxplus=arr[i];
					maxsum=maxsum+maxminus;
					maxminus=0;
					maxlen++;
					if (i==n-1) maxsum=maxsum+maxplus, maxplus=0;
				}
				else if (now==1&&now*arr[i]>0) {
					maxplus=max(maxplus, arr[i]);
					if (i==n-1) maxsum=maxsum+maxplus, maxplus=0;
				}
				else if (now==-1&&now*arr[i]>0) {
					maxminus=max(maxminus, arr[i]);
					if (i==n-1) maxsum=maxsum+maxminus, maxminus=0;
				}
			}
		}
		cout<<maxsum<<endl;
		maxsum=0;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
	int t;
	const int inf = 1e9;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		vector<long long>a(n + 1);
		vector<vector<pair<long long, int>>>dp(n + 1, vector<pair<long long, int>>(2, {-inf,0}));
		dp[0][0] = { 0,0 };
		dp[0][1] = { 0,0 };
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		for (int i = 1; i <= n;i++) {
			if (a[i] > 0) {
				if (dp[i - 1][1].second + 1 > dp[i - 1][0].second || (dp[i - 1][1].second + 1 == dp[i - 1][0].second && dp[i - 1][1].first + a[i] > dp[i - 1][0].first))
					dp[i][0] = { dp[i - 1][1].first + a[i],dp[i - 1][1].second + 1 };
				else
					dp[i][0] = dp[i - 1][0];
				dp[i][1] = dp[i - 1][1];
			}
			else {
				if (dp[i - 1][0].second + 1 > dp[i - 1][1].second || (dp[i - 1][0].second == dp[i - 1][1].second && dp[i - 1][0].first + a[i] > dp[i - 1][1].first))
					dp[i][1] = { dp[i - 1][0].first + a[i],dp[i - 1][0].second + 1 };
				else
					dp[i][1] = dp[i - 1][1];
				dp[i][0] = dp[i - 1][0];
			}
		}
		if (dp[n][0].second > dp[n][1].second)
			cout << dp[n][0].first << endl;
		else if (dp[n][0].second < dp[n][1].second)
			cout << dp[n][1].first << endl;
		else if(dp[n][0].first > dp[n][1].first)
			cout << dp[n][0].first << endl;
		else
			cout << dp[n][1].first << endl;
	}
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
	int t;
	const int inf = 1e9;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		vector<long long>a(n + 1);
		vector<vector<pair<long long, int>>>dp(n + 1, vector<pair<long long, int>>(2, { -inf,0 }));
		dp[0][0] = { 0,0 };
		dp[0][1] = { 0,0 };
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		for (int i = 1; i <= n;i++) {
			if (a[i] > 0) {
				if (dp[i - 1][1].second + 1 > dp[i - 1][0].second || (dp[i - 1][1].second + 1 == dp[i - 1][0].second && dp[i - 1][1].first + a[i] > dp[i - 1][0].first))
					dp[i][0] = { dp[i - 1][1].first + a[i],dp[i - 1][1].second + 1 };
				else
					dp[i][0] = dp[i - 1][0];
				dp[i][1] = dp[i - 1][1];
			}
			else {
				if (dp[i - 1][0].second + 1 > dp[i - 1][1].second || (dp[i - 1][0].second + 1 == dp[i - 1][1].second && dp[i - 1][0].first + a[i] > dp[i - 1][1].first))
					dp[i][1] = { dp[i - 1][0].first + a[i],dp[i - 1][0].second + 1 };
				else
					dp[i][1] = dp[i - 1][1];
				dp[i][0] = dp[i - 1][0];
			}
		}
		if (dp[n][0].second > dp[n][1].second)
			cout << dp[n][0].first << endl;
		else if (dp[n][0].second < dp[n][1].second)
			cout << dp[n][1].first << endl;
		else if (dp[n][0].first > dp[n][1].first)
			cout << dp[n][0].first << endl;
		else
			cout << dp[n][1].first << endl;
	}
}


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=2e5+10;
#define ll long long
int a[N];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		int flag=0;
		int max1=0,max2=0;
		ll sum=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			if(flag==0)
			{
				if(a[i]<0)
				{
					max2=a[i];
					flag=-1;
				}
				else
				{
					max1=a[i];
					flag=1;
				}
			}
			else if(flag==1)
			{
				if(a[i]<0)
				{
					sum+=(ll)max1;
					max2=a[i];
					flag=-1;
				}
				else
				{
					max1=max(max1,a[i]);

				}
			}
			else
			{
				if(a[i]<0)
				{

					max2=max(max2,a[i]);

				}
				else
				{
				    sum+=(ll)max2;
					flag=1;
					max1=a[i];

				}
			}
		}
		if(a[n]<0)
		{
			sum+=(ll)max2;
		}
		else sum+=(ll)max1;
		printf("%lld\n",sum);
	}
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <ctime>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cassert>

#define ll long long
#define forit(it, a) for(__typeof(a.begin()) it = a.begin(); it != a.end(); it++)
#define pb push_back
#define mp make_pair
using namespace std;

int main() {

	int count;
	cin >> count;

	for (int d = 0; d < count; ++d) {
		int s;
		cin >> s;

		vector<ll> v = {};

		for (int u = 0; u < s; ++u) {
			ll x;
			std::cin >> x;
			v.pb(x);
		}

		ll last = 0;

		ll total = 0;

		ll max = -INT64_MAX;

		for (auto k : v) {
			if (last == 0)
				max = k;
			else if (k > 0 != last > 0) {
				total += max;
				max = k;
			}
			else if (k > max) {
				max = k;
			}
			last = k;
		}
		total += max;
		cout << total << "\n";
	}
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
using namespace std;

void solve() {
    int n;
    cin >> n;

    pair<int, long long> pos = { 0, 0 }, neg = {0, 0};
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;

        if (x > 0) {
            if (neg.first + 1 > pos.first || neg.second + x > pos.second)
                pos = { neg.first + 1, neg.second + x };
        } else {
            if (pos.first + 1 > neg.first || pos.second + x > neg.second)
                neg = { pos.first + 1, pos.second + x };
        }
    }

    if (pos > neg)
        cout << pos.second << "\n";
    else
        cout << neg.second << "\n";
}

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

    int n;
    cin >> n;

    for (int i = 0; i < n; i++)
        solve();
}


//#include"pch.h"
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<numeric>
#include<cstring>
#include<string>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, p1 = 0, p2 = 1;
		long long int sum = 0;
		cin >> n;
		vector<long long int> a(n);
		for (int i = 0;i < n;i++)
			cin >> a[i];
		while (p1 < n && p2 < n)
		{
			long long int m = a[p1];
			while ((a[p1] * a[p2]) > 0)
			{
				m = max(m, a[p2]);
				if (p2 + 1 == n)
					break;
				p2++;
			}
			p1 = p2;
			p2++;
			sum += m;
		}
		if (a[p1 - 1] * a[p2 - 1] < 0)
			sum += a[p2 - 1];
		cout << sum << "\n";
	}
}


//#include"pch.h"
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<numeric>
#include<cstring>
#include<string>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, p1 = 0, p2 = 1;
		long long int sum = 0;
		cin >> n;
		vector<long long int> a(n);
		for (int i = 0;i < n;i++)
			cin >> a[i];
		if (n == 1)
		{
			cout << a[0] << "\n";
			continue;
		}
		while (p1 < n && p2 < n)
		{
			long long int m = a[p1];
			while ((a[p1] * a[p2]) > 0)
			{
				m = max(m, a[p2]);
				if (p2 + 1 == n)
					break;
				p2++;
			}
			p1 = p2;
			p2++;
			sum += m;
		}
		if (a[p1 - 1] * a[p2 - 1] < 0)
			sum += a[p2 - 1];
		cout << sum << "\n";
	}
}


#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>

using namespace std;

#ifdef ONLINE_JUDGE
#include <iostream>
#else
#include <fstream>
ifstream cin("input.txt");
ofstream cout("output.txt");
#endif

void solve()
{
	int n;
	cin >> n;
	vector<int> a(n);

	for (int& x : a) {
		cin >> x;
	}
	auto sign = [](int x) {
		return x < 0;
	};
	int lastChosen = a[0];
	long long sum = 0;
	for (int i = 1; i < n; i++) {
		if (sign(a[i]) == sign(a[i - 1])) {
			if (a[i] > lastChosen) {
				lastChosen = a[i];
			}
		}
		else {
			sum += lastChosen;
			lastChosen = a[i];
		}
	}
	sum += lastChosen;
	cout << sum << '\n';
}

int main()
{
	int t;
	cin >> t;
	while (t--) {
		solve();
	}

	return 0;
}


#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>

using namespace std;

#ifdef ONLINE_JUDGE
#include <iostream>
#else
#include <fstream>
ifstream cin("input.txt");
ofstream cout("output.txt");
#endif

void solve()
{
	int n;
	cin >> n;
	vector<int> a(n);

	for (int& x : a) {
		cin >> x;
	}
	auto sign = [](int x) {
		return x < 0;
	};
	int lastChosen = a[0];
	long long sum = 0;
	for (int i = 1; i < n; i++) {
		if (sign(a[i]) == sign(a[i - 1])) {
			if (a[i] > a[i - 1]) {
				lastChosen = a[i];
			}
		}
		else {
			sum += lastChosen;
			lastChosen = a[i];
		}
	}
	sum += lastChosen;
	cout << sum << '\n';
}

int main()
{
	int t;
	cin >> t;
	while (t--) {
		solve();
	}

	return 0;
}


//#include <algorithm>
//#include <list>
#include <iostream>
//#include <stack>
using namespace std;

int main(int argc, char* argv[])
{
	long long t, n, a, a_prev;
	cin >> t;
	for (; t-->0;)
	{
		cin >> n;

		long long sum = 0;

		cin >> a_prev;
		for (; n-->1; )
		{
			cin >> a;
			if (a * a_prev < 0)
			{
				sum += a_prev;
				a_prev = a;
			}
			else if (a_prev < a)
			{
				a_prev = a;
			}
		}

		sum += a_prev;
		cout << sum << endl;
	}
}


//#include <algorithm>
//#include <list>
#include <iostream>
//#include <stack>
using namespace std;

int main(int argc, char* argv[])
{
	int t, n, a, a_prev;
	cin >> t;
	for (; t-->0;)
	{
		cin >> n;

		long long sum = 0;

		cin >> a_prev;
		for (; n-->1; )
		{
			cin >> a;
			if (a * a_prev < 0)
			{
				sum += a_prev;
				a_prev = a;
			}
			else if (a_prev < a)
			{
				a_prev = a;
			}
		}

		sum += a_prev;
		cout << sum << endl;
	}
}


#include<stdio.h>
#include<algorithm>

#define ll long long
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        ll ans;
        b=0,ans=0,maxn=-1000000005;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            if(a==0) continue;
            if(b*a<0)
                test=0,ans+=maxn,maxn=-1000000005;
            else
                test=1;
            maxn=max(a,maxn);
            b=a;
        }
        ans+=maxn;
        printf("%lld\n",ans);

    }
    return 0;
}


#include<stdio.h>
#include<algorithm>

#define ll long long
const int INF=-1e9-5;
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        int ans;
        b=0,ans=0,maxn=INF;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            if(b*a<0)         //判断是否符号不同了
                ans+=maxn,maxn=INF;
            maxn=max(a,maxn);       //记录同符号最大值
            b=a;              //上一个存在b里面
        }
        ans+=maxn;       //最后一个同符号要算进去
        printf("%d\n",ans);

    }
    return 0;
}


#include<stdio.h>
#include<algorithm>

#define ll long long
const int INF=-1e9-5;
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        ll ans;
        b=0,ans=0,maxn=INF;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            if((ll)a*(ll)b<0)         //判断是否符号不同了
                ans+=maxn,maxn=INF;
            maxn=max(a,maxn);       //记录同符号最大值
            b=a;              //上一个存在b里面
        }
        ans+=maxn;       //最后一个同符号要算进去
        printf("%lld\n",ans);

    }
    return 0;
}


#include<stdio.h>
#include<algorithm>

#define ll long long
const int INF=-1e9-5;
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        ll ans;
        b=0,ans=0,maxn=INF;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            if((ll)(b*a)<0)         //判断是否符号不同了
                ans+=maxn,maxn=INF;
            maxn=max(a,maxn);       //记录同符号最大值
            b=a;              //上一个存在b里面
        }
        ans+=maxn;       //最后一个同符号要算进去
        printf("%lld\n",ans);

    }
    return 0;
}


#include<stdio.h>
#include<algorithm>

#define ll long long
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        ll ans;
        b=0,ans=0,maxn=-1000000005;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            if(b*a<0)
                test=0,ans+=maxn,maxn=-1000000005;
            else
                test=1;
            maxn=max(a,maxn);
            b=a;
        }
        ans+=maxn;
        printf("%lld\n",ans);

    }
    return 0;
}


#include<stdio.h>
#include<algorithm>

#define ll long long
const int INF=-1e9-5;
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        ll ans;
        b=0,ans=0,maxn=INF;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            ll c=(ll)a*(ll)b;
            if(c<0)         //判断是否符号不同了
                ans+=maxn,maxn=INF;
            maxn=max(a,maxn);       //记录同符号最大值
            b=a;              //上一个存在b里面
        }
        ans+=maxn;       //最后一个同符号要算进去
        printf("%lld\n",ans);

    }
    return 0;
}


#include<stdio.h>
#include<algorithm>

#define ll long long
const int INF=-1e9-5;
using namespace std;

int main()
{
    int t,a,n,b,maxn;
    scanf("%d",&t);
    while(t--)
    {
        int test=1;
        ll ans;
        b=0,ans=0,maxn=INF;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            ll c=a*b;
            if(c<0)         //判断是否符号不同了
                ans+=maxn,maxn=INF;
            maxn=max(a,maxn);       //记录同符号最大值
            b=a;              //上一个存在b里面
        }
        ans+=maxn;       //最后一个同符号要算进去
        printf("%lld\n",ans);

    }
    return 0;
}


#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

int t;
int n;
int a[N];

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

	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
			scanf("%d",&a[i]);
		LL sum=0;
		for(int i=1;i<=n;i++)
		{
			if(a[i]>0)
			{
				int t=0;
				while(i<=n&&a[i]>0)
					t=max(t,a[i]),i++;
				i--;
				sum+=t;
			}
			else
			{
				int t=-1e9-10;
				while(i<=n&&a[i]<0)
					t=max(a[i],t),i++;
				i--;
				sum+=t;
			}
		}
		printf("%lld\n",sum);
	}

	return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
typedef long long ll;
using  namespace  std;
const int M = 2e5 + 10;
const int inf = 0x3f3f3f3f;
int n, k;
int a[M];

int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d", &n);
		ll ans = 0;
		for (int i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		int p = a[1] > 0 ? 1 : 0;
		int q = -1;
		int maxi = a[1];
		for (int i = 2; i <= n; i++)
		{
			q = a[i] > 0 ? 1 : 0;
			if (p == q)
			{
				maxi = max(maxi, a[i]);
			}
			else
			{
				ans+=maxi;
				maxi = a[i];
				p = q;
			}
		}
		ans += maxi;
		printf("%lld\n", ans);
	}
}


//#include <iostream>
//using namespace std;
//
//struct Movements{
//    int r;
//    int c;
//    int x;
//    int t;
//};
//Movements movement[10000];
//int arr[100][100]={0};
//int main(){
//    int m,n,q;
//
//    cin>>n>>m>>q;
//
//    for(int i=0;i<q;i++){
//        cin>>movement[i].t;
//
//        if(movement[i].t==1){
//            cin>>movement[i].r;
//        }
//        else if(movement[i].t==2){
//            cin>>movement[i].c;
//        }
//        else cin>>movement[i].r>>movement[i].c>>movement[i].x;
//    }
//
//    for(int i=q-1;i>=0;i--){
//
//        if(movement[i].t==1){
//
//            int r=movement[i].r-1;
//            int k=arr[r][m-1];
//
//            for(int z=m-1;z>0;z--){
//                arr[r][z]=arr[r][z-1];
//            }
//            arr[r][0]=k;
//        }
//
//
//        else if(movement[i].t==2){
//            int c=movement[i].c-1;
//            int k=arr[n-1][c];
//            for(int j=n-1;j>0;j--){
//                arr[j][c]=arr[j-1][c];
//            }
//            arr[0][c]=k;
//        }
//
//
//        else{
//            arr[movement[i].r - 1][movement[i].c - 1]=movement[i].x;
//        }
//    }
//
//
//    for(int i=0;i<n;i++){
//        for(int j=0;j<m;j++){
//            cout<<arr[i][j]<<' ';
//        }
//
//        cout<<endl;
//    }
//return 0;}
//

//#include <iostream>
//using namespace std;
//#include <cstring>
//
//    bool IsUpperCaseVowel(char ch){
//        if ( ch=='A' || ch=='E' || ch=='O' || ch=='I' || ch=='U')return true;
//        return false;
//    }
//
//
//     bool IsLowerCaseVowel(char ch){
//        if( ch=='a' || ch=='e' || ch=='o' || ch=='i' || ch=='u')return true;
//        return false;
//    }
//
//    bool IsOnly(char ch[]){
//        for(int i=0;ch[i]!='\0';i++){
//            if(IsLowerCaseVowel(ch[i]) || IsUpperCaseVowel(ch[i]))return false;
//        }
//        return true;
//    }
//int main(){
//    char c[101],c_new[202];
//    cin.getline(c,101,'\n');
//    c[strlen(c)]='\0';
//
//    int ind_c=0;
//
//    for(int i=0;c[i]!='\0';i++){
//        if(!(IsLowerCaseVowel(c[i]) || IsUpperCaseVowel(c[i])) && c[i]!='y' && c[i]!='Y'){
////(c[i]=='y' && (IsOnly(c) || (!(IsLowerCaseVowel(c[i+1]) || IsUpperCaseVowel(c[i+1])) && !(IsLowerCaseVowel (c[i-1]) || IsUpperCaseVowel (c[i-1])))))){
//            if((c[i]>='a' && c[i]<='z') || (c[i]>='A' && c[i]<='Z')){
//                c_new[ind_c]='.';
//                ind_c++;
//                if(c[i]<'a'){
//                    c[i]+=32;
//                }
//                c_new[ind_c]=c[i];
//                ind_c++;
//            }
//        }
//    }
//    if(c_new[ind_c-1]=='y'){
//        c_new[ind_c-1]='\0';
//    }
//    else
//    c_new[ind_c]='\0';
//
//    cout<<c_new<<endl;
//return 0;
//}
//
//
////#include <iostream>
////using namespace std;
////int main(){
////    char a='a';
//////    a-=32;
////    cout<<char(a-' ');
////return 0;}

bool ContainsPositiveAndNegative(int x[],int z){
    for(int i=0;i<z-1;i++){
        if((x[i]<0 && x[i+1]>0) || (x[i]>0 && x[i+1]<0)) return true;
    }
    return false;
}

int MaxElement(int x[],int y){
    int max_=x[0];
    for(int i=1;i<y;i++){
        if(x[i]>max_){
            max_=x[i];
        }
    }
    return max_;
}

int MaxSum(int x[],int y){
//    1 2 3 -1 -2
    int len,max_len=-1,max_sum=-10000000000;
    int flag=0,sum=0;

    for(int i=0;i<y-1;i++){
         int last_element=x[i];
         flag=0;
         sum=x[i];
         len=1;
         for(int j=i+1;j<y;j++){
            if(x[j]<0 && last_element>0 || x[j]>0 && last_element<0){
                last_element=x[j];
                len++;
                flag=1;
                sum+=x[j];

            }
         }
         if(flag && len>max_len){
            max_len=len;
         }

         if(flag && sum>max_sum && len==max_len){
            max_sum=sum;
         }
    }
    return max_sum;

}
#include <iostream>
using namespace std;
int main(){
    int t,n,arr[200000];
    long long int results[10000];
    cin>>t;

    for(int i=0;i<t;i++){
        cin>>n;
        for(int j=0;j<n;j++){
            cin>>arr[j];
        }
        if(ContainsPositiveAndNegative(arr,n)){

//    1 2 3 -1 -2
            int len,max_len=-1;
            long long max_sum=-100000000000;
            int flag=0;
            long long sum=0;

            for(int i=0;i<n-1;i++){
                 long int last_element=arr[i];
                 flag=0;
                 sum=arr[i];
                 len=1;
                 for(int j=i+1;j<n;j++){
                    if(arr[j]<0 && last_element>0 || arr[j]>0 && last_element<0){
                        last_element=arr[j];
                        len++;
                        flag=1;
                        sum+=arr[j];
                    }
                 }
                 if(flag && len>max_len){
                    max_len=len;
                 }

                 if(flag && sum>max_sum && len==max_len){
                    max_sum=sum;
                 }

            }
                    results[i]=max_sum;
        }

        else{
          results[i]=MaxElement(arr,n);
        }

    }

    for(int i=0;i<t;i++){
        cout<<results[i]<<endl;
    }
return 0;}


//#include <iostream>
//using namespace std;
//
//struct Movements{
//    int r;
//    int c;
//    int x;
//    int t;
//};
//Movements movement[10000];
//int arr[100][100]={0};
//int main(){
//    int m,n,q;
//
//    cin>>n>>m>>q;
//
//    for(int i=0;i<q;i++){
//        cin>>movement[i].t;
//
//        if(movement[i].t==1){
//            cin>>movement[i].r;
//        }
//        else if(movement[i].t==2){
//            cin>>movement[i].c;
//        }
//        else cin>>movement[i].r>>movement[i].c>>movement[i].x;
//    }
//
//    for(int i=q-1;i>=0;i--){
//
//        if(movement[i].t==1){
//
//            int r=movement[i].r-1;
//            int k=arr[r][m-1];
//
//            for(int z=m-1;z>0;z--){
//                arr[r][z]=arr[r][z-1];
//            }
//            arr[r][0]=k;
//        }
//
//
//        else if(movement[i].t==2){
//            int c=movement[i].c-1;
//            int k=arr[n-1][c];
//            for(int j=n-1;j>0;j--){
//                arr[j][c]=arr[j-1][c];
//            }
//            arr[0][c]=k;
//        }
//
//
//        else{
//            arr[movement[i].r - 1][movement[i].c - 1]=movement[i].x;
//        }
//    }
//
//
//    for(int i=0;i<n;i++){
//        for(int j=0;j<m;j++){
//            cout<<arr[i][j]<<' ';
//        }
//
//        cout<<endl;
//    }
//return 0;}
//

//#include <iostream>
//using namespace std;
//#include <cstring>
//
//    bool IsUpperCaseVowel(char ch){
//        if ( ch=='A' || ch=='E' || ch=='O' || ch=='I' || ch=='U')return true;
//        return false;
//    }
//
//
//     bool IsLowerCaseVowel(char ch){
//        if( ch=='a' || ch=='e' || ch=='o' || ch=='i' || ch=='u')return true;
//        return false;
//    }
//
//    bool IsOnly(char ch[]){
//        for(int i=0;ch[i]!='\0';i++){
//            if(IsLowerCaseVowel(ch[i]) || IsUpperCaseVowel(ch[i]))return false;
//        }
//        return true;
//    }
//int main(){
//    char c[101],c_new[202];
//    cin.getline(c,101,'\n');
//    c[strlen(c)]='\0';
//
//    int ind_c=0;
//
//    for(int i=0;c[i]!='\0';i++){
//        if(!(IsLowerCaseVowel(c[i]) || IsUpperCaseVowel(c[i])) && c[i]!='y' && c[i]!='Y'){
////(c[i]=='y' && (IsOnly(c) || (!(IsLowerCaseVowel(c[i+1]) || IsUpperCaseVowel(c[i+1])) && !(IsLowerCaseVowel (c[i-1]) || IsUpperCaseVowel (c[i-1])))))){
//            if((c[i]>='a' && c[i]<='z') || (c[i]>='A' && c[i]<='Z')){
//                c_new[ind_c]='.';
//                ind_c++;
//                if(c[i]<'a'){
//                    c[i]+=32;
//                }
//                c_new[ind_c]=c[i];
//                ind_c++;
//            }
//        }
//    }
//    if(c_new[ind_c-1]=='y'){
//        c_new[ind_c-1]='\0';
//    }
//    else
//    c_new[ind_c]='\0';
//
//    cout<<c_new<<endl;
//return 0;
//}
//
//
////#include <iostream>
////using namespace std;
////int main(){
////    char a='a';
//////    a-=32;
////    cout<<char(a-' ');
////return 0;}

    char sign(int x){
        if(x>0)return 1;
        else if(x<0)return -1;
        else return 0;
    }
#include <iostream>
using namespace std;
int main(){

	int t;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		int a[200000];
		for(int i=0;i<n;i++)cin>>a[i];
		long long sum = 0;
//		5
//        1 2 3 -1 -2

//10
//-2 -8 3 8 -4 -15 5 -2 -3 1
		for(int i=0;i<n;i++){
            int current=a[i];
            int j=i;
            while(j<n && sign(a[i])==sign(a[j])){
                current=max(a[i],current);
                j++;
            }
            i=j-1;
            sum+=current;
		}
		cout << sum << endl;
	}

return 0;}


//#include <iostream>
//using namespace std;
//
//struct Movements{
//    int r;
//    int c;
//    int x;
//    int t;
//};
//Movements movement[10000];
//int arr[100][100]={0};
//int main(){
//    int m,n,q;
//
//    cin>>n>>m>>q;
//
//    for(int i=0;i<q;i++){
//        cin>>movement[i].t;
//
//        if(movement[i].t==1){
//            cin>>movement[i].r;
//        }
//        else if(movement[i].t==2){
//            cin>>movement[i].c;
//        }
//        else cin>>movement[i].r>>movement[i].c>>movement[i].x;
//    }
//
//    for(int i=q-1;i>=0;i--){
//
//        if(movement[i].t==1){
//
//            int r=movement[i].r-1;
//            int k=arr[r][m-1];
//
//            for(int z=m-1;z>0;z--){
//                arr[r][z]=arr[r][z-1];
//            }
//            arr[r][0]=k;
//        }
//
//
//        else if(movement[i].t==2){
//            int c=movement[i].c-1;
//            int k=arr[n-1][c];
//            for(int j=n-1;j>0;j--){
//                arr[j][c]=arr[j-1][c];
//            }
//            arr[0][c]=k;
//        }
//
//
//        else{
//            arr[movement[i].r - 1][movement[i].c - 1]=movement[i].x;
//        }
//    }
//
//
//    for(int i=0;i<n;i++){
//        for(int j=0;j<m;j++){
//            cout<<arr[i][j]<<' ';
//        }
//
//        cout<<endl;
//    }
//return 0;}
//

//#include <iostream>
//using namespace std;
//#include <cstring>
//
//    bool IsUpperCaseVowel(char ch){
//        if ( ch=='A' || ch=='E' || ch=='O' || ch=='I' || ch=='U')return true;
//        return false;
//    }
//
//
//     bool IsLowerCaseVowel(char ch){
//        if( ch=='a' || ch=='e' || ch=='o' || ch=='i' || ch=='u')return true;
//        return false;
//    }
//
//    bool IsOnly(char ch[]){
//        for(int i=0;ch[i]!='\0';i++){
//            if(IsLowerCaseVowel(ch[i]) || IsUpperCaseVowel(ch[i]))return false;
//        }
//        return true;
//    }
//int main(){
//    char c[101],c_new[202];
//    cin.getline(c,101,'\n');
//    c[strlen(c)]='\0';
//
//    int ind_c=0;
//
//    for(int i=0;c[i]!='\0';i++){
//        if(!(IsLowerCaseVowel(c[i]) || IsUpperCaseVowel(c[i])) && c[i]!='y' && c[i]!='Y'){
////(c[i]=='y' && (IsOnly(c) || (!(IsLowerCaseVowel(c[i+1]) || IsUpperCaseVowel(c[i+1])) && !(IsLowerCaseVowel (c[i-1]) || IsUpperCaseVowel (c[i-1])))))){
//            if((c[i]>='a' && c[i]<='z') || (c[i]>='A' && c[i]<='Z')){
//                c_new[ind_c]='.';
//                ind_c++;
//                if(c[i]<'a'){
//                    c[i]+=32;
//                }
//                c_new[ind_c]=c[i];
//                ind_c++;
//            }
//        }
//    }
//    if(c_new[ind_c-1]=='y'){
//        c_new[ind_c-1]='\0';
//    }
//    else
//    c_new[ind_c]='\0';
//
//    cout<<c_new<<endl;
//return 0;
//}
//
//
////#include <iostream>
////using namespace std;
////int main(){
////    char a='a';
//////    a-=32;
////    cout<<char(a-' ');
////return 0;}

    int sign(int x){
        if(x>0)return 1;
        else if(x<0)return -1;
        else return 0;
    }
#include <iostream>
using namespace std;
int main(){

	int t;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		int a[200000];
		for(int i=0;i<n;i++)cin>>a[i];
		long long sum = 0;
//		5
//        1 2 3 -1 -2

//10
//-2 -8 3 8 -4 -15 5 -2 -3 1
		for(int i=0;i<n;i++){
            int current=a[i];
            int j=i;
            while(j<n && sign(a[i])==sign(a[j])){
                current=max(a[j],current);
                j++;
            }
            i=j-1;
            sum+=current;
		}
		cout << sum << endl;
	}

return 0;}


#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
#define pi acos(-1)
const int manx=2e5+5;
typedef long long ll;
int a[manx];
int n;
void scan(){
for (int i = 0;i < n;i ++) 	scanf("%d",&a[i]);
}

int main()
{
    int repeat;
    scanf("%d",&repeat);

    int k,f,m,s;
    while (repeat--) {
        scanf("%d",&n);
        scan();
	int b[manx];
	k=0;
        s = (a[0] / abs(a[0])) * -1;
        f = 1;
        m = 0;
        for (int i = 0;i < n;i ++) {
            if (a[i] / abs(a[i]) != s) {
                if (f == 1) f = 0;
                else b[k ++] = m;
                m = a[i];
                s = a[i] / abs(a[i]);
            } else {
                m = max(m,a[i]);
            }
        }
        b[k ++] = m;
		ll sum = 0;
        for (int i = 0;i < k;i ++)sum += b[i];
         cout<<sum<<endl;

    }
    return 0;
}


#include <stdio.h>
#include <iostream>
#include <set>
#include <bitset>
#include <map>
#include <stack>
#include <algorithm>
#include <math.h>
#include <queue>
#include <vector>
#include <string.h>
#define mem(x,b) memset(x,b,sizeof(x))
#define mp(a,b) make_pair(a,b)
#define debug(a) cout<<a<<endl
#define maxn 200005
using namespace std;
typedef long long ll;
typedef double db;
const int mod=1e9+7;
int a[maxn];
int n;
ll ans;
int main()
{
    int t=1;
    scanf("%d",&t);
    while(t--){
    	ans=0;
    	scanf("%d",&n);
    	for(int i=0;i<n;i++){
    		scanf("%d",&a[i]);
    	}
    	int i=0;
    	int maxx;
    	if(a[0]>0){
    		while(1){
    			maxx=-2e9;
    			while(a[i]>0){
    				maxx=max(maxx,a[i]);
    				i++;
    				if(i>=n)break;
    			}
    			ans+=maxx;
    			if(i>=n)break;
    			maxx=-2e9;
    			while(a[i]<0){
    				maxx=max(maxx,a[i]);
    				i++;
					if(i>=n)break;
    			}
    			ans+=maxx;
    			if(i>=n)break;
    		}
    	}else{
    		while(1){
    			maxx=-2e9;
    			while(a[i]<0){
    				maxx=max(maxx,a[i]);
    				i++;
    				if(i>=n)break;
    			}
    			ans+=maxx;
    			if(i>=n)break;
    			maxx=-2e9;
    			while(a[i]>0){
    				maxx=max(maxx,a[i]);
    				i++;
					if(i>=n)break;
    			}
    			ans+=maxx;
    			if(i>=n)break;
    		}
    	}
    	printf("%lld\n",ans);
    }
    return 0;
}


#include<iostream>
#include<cstdio>
using namespace std;
int t;

int main()
{
    cin>>t;
    while(t--)
    {
        long long n, a[200009], ans=0, flag;
        cin>>n;
        for(int i=0; i<n; i++)
        {
            cin>>a[i];
        }
        ans+=a[0];
        flag=a[0];
        for(int i=1; i<n; i++)
        {
            if(a[i]>0&&a[i-1]>0)
            {
                if(a[i]>flag)
                {
                    ans-=a[i-1];
                    ans+=a[i];
                    flag=a[i];
                }
            }
            else if(a[i]<0&&a[i-1]<0)
            {
                if(a[i]>flag)
                {
                    ans-=a[i-1];
                    ans+=a[i];
                    flag=a[i];
                }
            }
            else
            {
                ans+=a[i];
                flag=a[i];
            }
       }
       cout<<ans<<endl;
    }
    return 0;
}


#include<iostream>
#include<cstdio>
using namespace std;
int t;

int main()
{
    cin>>t;
    while(t--)
    {
        long long n, a[200009], ans=0, flag;
        cin>>n;
        for(int i=0; i<n; i++)
        {
            cin>>a[i];
        }
        ans+=a[0];
        flag=a[0];
        for(int i=1; i<n; i++)
        {
            if(a[i]>0&&a[i-1]>0)
            {
                if(a[i]>flag)
                {
                    ans-=flag;
                    ans+=a[i];
                    flag=a[i];
                }
            }
            else if(a[i]<0&&a[i-1]<0)
            {
                if(a[i]>flag)
                {
                    ans-=flag;
                    ans+=a[i];
                    flag=a[i];
                }
            }
            else
            {
                ans+=a[i];
                flag=a[i];
            }
       }
       cout<<ans<<endl;
    }
    return 0;
}


#include<iostream>
using namespace std;
int main() {
	int num[200005];
	int t;
	cin >> t;
	while (t--) {
		memset(num, 0, sizeof(num));
		int n;
		long long mmax;
		long long ans = 0;
		int flag = 0;
		cin >> n;
		for (int i = 0;i < n;i++) {
			cin >> num[i];
		}
		mmax = num[0];
		for (int i = 1;i < n;i++) {
			if (num[i] > 0 && num[i-1]>0 && num[i] > mmax) {
				mmax = num[i];
			}
			if (num[i] < 0 && num[i - 1] > 0) {
				flag = 1;
				ans += mmax;
				mmax = num[i];
			}
			if (num[i] < 0 && num[i - 1]<0 && num[i] > mmax) {
				mmax = num[i];
			}
			if (num[i] > 0 && num[i - 1] < 0) {
				flag = 1;
				ans += mmax;
				mmax = num[i];
			}
		}
		ans += mmax;
		if (flag == 1) cout << ans << endl;
		else cout << mmax << endl;
	}
	return 0;
}


t = int(input())

for i in range(t):
    n = int(input())

    if n == 1:
        print(8)
    elif n % 2 != 0:
        print(int('9' * (n-1) + '8'))
    else:
        print(int('8' * n))


for i in range(int(input())):
    n = int(input())
    if n==1:
        print(8)
    else:
        k = '1001'*n
        r = k[:-n]
        sahi = len(r)//4
        # ans = '9'*sahi
        ans = ''
        rem = sahi*4
        rest = k[-n:]
        zeros = '0'*len(rest)
        r += zeros
        for i in range(0,len(r),4):
            now = r[i:i+4]
            intt = int(now,2)
            ans+= str(intt)

        print(ans)


for i in range(int(input())):
    n = int(input())
    if n==1:
        print(8)
    else:
        s = '9'*(n-1)
        s = s+'8'
        print(s)


import math
for i in range(int(input())):
	n = int(input())
	if n==1:
	    print(8)
	else:
		v = math.ceil(n/4)
		nine = n-v
		ans = '9'*nine
		e = '8'*v
		ans = ans+e
		print(ans)
	    # k = '1001'*n
	    # r = k[:-n]
	    # sahi = len(r)//4
	    # # ans = '9'*sahi
	    # ans = ''
	    # rem = sahi*4
	    # rest = k[-n:]
	    # zeros = '8'*len(rest)
	    # r += zeros
	    # for i in range(0,len(r),4):
	    #     now = r[i:i+4]
	    #     intt = int(now,2)
	    #     ans+= str(intt)

	    # print(ans)


import math
for i in range(int(input())):
n = int(input())
if n==1:
    print(8)
else:
	v = math.ceil(n/4)
	nine = n-v
	ans = '9'*nine
	e = '8'*v
	ans = ans+e
	print(ans)
    # k = '1001'*n
    # r = k[:-n]
    # sahi = len(r)//4
    # # ans = '9'*sahi
    # ans = ''
    # rem = sahi*4
    # rest = k[-n:]
    # zeros = '8'*len(rest)
    # r += zeros
    # for i in range(0,len(r),4):
    #     now = r[i:i+4]
    #     intt = int(now,2)
    #     ans+= str(intt)

    # print(ans)


class Main:
    def main(self):
        t = int(input())
        for t1 in range(0, t):
            n = int(input())
            rm = 0
            result = 0
            for x in reversed(range(pow(10, n - 1), pow(10, n))):
                k = "".join(map(lambda x1 : str(bin(int(x1)))[2:], str(x)))
                r = int(k[:-n], 2) if len(k[:-n]) > 0 else 0
                if rm == 0:
                    rm = r
                    result = x
                elif rm == r:
                    result = x
                else:
                    break
            print("{0}".format(result))

Main().main()


class Main:
    def main(self):
        t = int(input())
        for t1 in range(0, t):
            n = int(input())
            rm = 0
            result = 0
            for x in range(pow(10, n - 1), pow(10, n)):
                k = "".join(map(lambda x1 : str(bin(int(x1)))[2:], str(x)))
                r = int(k[:-n], 2) if len(k[:-n]) > 0 else 0
                if rm < r:
                    rm = r
                    result = x
            print("{0}".format(result))

Main().main()


class Main:
    def main(self):
        t = int(input())
        for t1 in range(0, t):
            n = int(input())
            d = (n - 1) // 4 + 1
            result = "9" * (n - d) + "8" * d
            print("{0}".format(result))

Main().main()


# your code goes here
import math
for _ in range(int(input())):
	n=int(input())
	if(n==1):
		print(8)
	if(n==2):
		print("98")
	else:
		y=math.log2(n)
		y=math.floor(y)
		if(y==math.log2(n)):
			str="8"*(y-1)
			str+="9"*(n-y+1)
			str=str[::-1]
			print(str)
			continue
		str="8"*y
		str+="9"*(n-y)
		str=str[::-1]
		print(str)


# your code goes here
import math
for _ in range(int(input())):

	n=int(input())
	a=n//4
	if n%4==0:
		for i in range(1,n-a+1):
			print("9",end="")
		for i in range(n-a+1,n+1):
			print("8",end="")
	else:
		for i in range(1,n-a):
			print("9",end="")
		for i in range(n-a,n+1):
			print("8",end="")
	print("")


# your code goes here
import math
for _ in range(int(input())):

	n=int(input())
	if(n==2):
		print("98")
		continue
	if(n==1):
		print(8)
	else:
		y=n/4
		y=math.ceil(y)
		str="8"*y
		str+="9"*(n-y)
		str=str[::-1]
		print(str)


# your code goes here
import math
for _ in range(int(input())):
	n=int(input())
	if(n==1):
		print(8)
	else:
		y=math.log2(n)
		y=math.floor(y)
		if(y==math.log2(n)):
			str="8"*(y-1)
			str+="9"*(n-y+1)
			str=str[::-1]
			print(str)
			continue
		str="8"*y
		str+="9"*(n-y)
		str=str[::-1]
		print(str)


# your code goes here
import math
for _ in range(int(input())):

	n=int(input())
	if(n==2):
		print("98")
		continue
	if(n==1):
		print(8)
	else:
		y=math.log2(n)
		y=math.floor(y)
		if(y==math.log2(n)):

			str="9"*(n-y+1)
			str+="8"*(y-1)

			print(str)
			continue
		str="8"*y
		str+="9"*(n-y)
		str=str[::-1]
		print(str)


for _ in range(int(input())):
    z=1
    a = int(input())
    if a-1>=4:
        z = a//4
    print((a-z)*'9'+'8'*z)


for _ in range(int(input())):
    a = int(input())
    print((a-1)*'9'+'8')


for _ in range(int(input())):
    a = int(input())
    z = (a-1)//4
    z+=1
    print((a-z)*'9'+'8'*z)


for _ in range(int(input())):
    z=1
    a = int(input())
    if a>=5:
        z = a//5
    print((a-z)*'9'+'8'*z)


t=int(input())
for tst in range(t):
    n=int(input())
    s=''
    s+='9'*(n-int(n/4)-1)
    s+='8'*(int(n/4)+1)
    print(s)


t=int(input())
for tst in range(t):
    n=int(input())
    s=''
    s+='9'*(n-1)
    s+='8'
    print(s)


t=int(input())
for tst in range(t):
    n=int(input())
    s=''
    if n%4==0:
        k=int(n/4)
    else:
        k=int(n/4)+1
    s+='9'*(n-k)
    s+='8'*(k)
    print(s)


for _ in range(int(input())):
    n = int(input())
    e = n // 4
    if n % 4:
        e += 1
    m = int('9' * (n - e) + '8' * e)
    print(m)


for _ in range(int(input())):
    n = int(input())
    e = n // 4
    print('9' * (n - e) + '8' * e)


for _ in range(int(input())):
    n = int(input())
    e = 0 - (-n // 4)
    print('9' * (n - e) + '8' * e)


t=int(input())
for _ in range(t):
    n=int(input())
    a=""
    for i in range(n-1):
        a+='9'
    print(a+'8')


from collections import deque
from math import *
import heapq
from random import *
import sys

t=int(input())
for i in range(t):

    n=int(input())
    # if n==2:
    #     print(98)
    #     continue
    # if n==3:
    #     print(998)
    #     continue

    if (n)%4==0:
        val=n//4
        diff=n-val

        print(int("9"*diff+ "8"*val))

    else:
        val=n//4
        diff=n-val

        print(int("9"*(diff-1) + "8"+"8"*val))
    # if (n)%4==0:
    #     print(int("9"*n))

    # else:
    #     s=""
    #     for j in range(n-1):
    #         s+="9"
    #     s+="8"
    #     print(int(s))


from collections import deque
from math import *
import heapq
from random import *
import sys

t=int(input())
for i in range(t):

    n=int(input())
    # if n==2:
    #     print(98)
    #     continue
    # if n==3:
    #     print(998)
    #     continue
    if (n)%4==0:
        val=n//4
        diff=n-val

        print(int("9"*diff+ "0"*val))

    else:
        val=n//4
        diff=n-val

        print(int("9"*(diff-1) + "8"+"0"*val))


from collections import deque
from math import *
import heapq
from random import *
import sys

t=int(input())
for i in range(t):

    n=int(input())
    s=""
    for j in range(n-1):
        s+="9"
    s+="8"
    print(int(s))


from collections import deque
from math import *
import heapq
from random import *
import sys

t=int(input())
for i in range(t):

    n=int(input())
    if (n)%4==0:
        print(int("9"*n))

    else:
        s=""
        for j in range(n-1):
            s+="9"
        s+="8"
        print(int(s))


t=int(input())
import math
while t>0:
    t-=1
    a=int(input())
    j=math.ceil(a/4)
    for i in range(a-j):
        print('9',end='')
    for i in range(j):
        print('8',end='')
    print()


t=int(input())
while t>0:
    t-=1
    a=int(input())
    j=a//4
    for i in range(a-j-1):
        print('9',end='')
    for i in range(j+1):
        print('8',end='')
    print()


import sys
from math import sqrt
inpt = sys.stdin.readline

def inp():
    return(int(inpt()))

def inlist():
    return(list(map(int,inpt().split())))

def instr():
    s = inpt()
    return(list(s[:len(s)-1]))

def invr():
    return(map(int,inpt().split()))

def main():

    t = inp()

    for l in range(t):

        n = inp()
        x = n/4
        for i in range(int(n-x)):
            print(9,sep='',end='')
        for i in range(int(x)+1):
            print(8,sep='',end='')
        print()

main()


import sys
from math import sqrt
inpt = sys.stdin.readline

def inp():
    return(int(inpt()))

def inlist():
    return(list(map(int,inpt().split())))

def instr():
    s = inpt()
    return(list(s[:len(s)-1]))

def invr():
    return(map(int,inpt().split()))

def main():

    t = inp()

    for l in range(t):

        n = inp()
        x = n/4
        for i in range(int(n-x)):
            print(9,sep='',end='')
        for i in range(int(x+0.999)):
            print(8,sep='',end='')
        print()

main()


import sys
from math import sqrt
inpt = sys.stdin.readline

def inp():
    return(int(inpt()))

def inlist():
    return(list(map(int,inpt().split())))

def instr():
    s = inpt()
    return(list(s[:len(s)-1]))

def invr():
    return(map(int,inpt().split()))

def main():

    t = inp()

    for l in range(t):

        n = inp()
        for i in range(n-1):
            print(9,sep='',end='')
        print(8)

main()


import sys
from math import sqrt
inpt = sys.stdin.readline

def inp():
    return(int(inpt()))

def inlist():
    return(list(map(int,inpt().split())))

def instr():
    s = inpt()
    return(list(s[:len(s)-1]))

def invr():
    return(map(int,inpt().split()))

def main():

    t = inp()

    for l in range(t):

        n = inp()
        x = n/4
        for i in range(int(n-x)):
            print(9,sep='',end='')
        for i in range(int(x+0.999)):
            print(8,sep='',end='')

main()


for _ in range(int(input())):
    n=int(input())
    print("9"*(n-ceil(n//3))+"8"*(ceil(n//3)))


for _ in range(int(input())):
    n=int(input())
    print("9"*(n-ceil(n/3))+"8"*(ceil(n/3)))


from math import ceil
for _ in range(int(input())):
    n=int(input())
    x=ceil(n/3)
    print("9"*(n-x)+"8"*x)


for _ in range(int(input())):
    n=int(input())
    print("9"*(n-1)+"8")


for _ in range(int(input())):
    n=int(input())
    print("9"*(n-n//3)+"8"*(n//3))


from math import ceil
for _ in range(int(input())):
    n=int(input())
    x=ceil(n/4)
    print("9"*(n-x)+"8"*x)


for _ in range(int(input())):
    n=int(input())
    x=ceil(n/3)
    print("9"*(n-x)+"8"*x)


for I in range(int(input())):
    n = int(input())
    needed = (n*4)-n
    nine = needed//4
    rem = needed%4

    result = nine*'9'

    if rem>0:
        maxi = -1
        res = -1
        for i in range(10):
            temp = '000' + bin(i)[2:]
            temp = temp[-4:]

            if int(temp[:rem])>maxi:
                maxi = int(temp[:rem])
                res = i

        result+=str(res)

    for i in range(n-len(result)):
        result+='0'

    print(result)


for I in range(int(input())):
    n = int(input())
    needed = (n*4)-n
    nine = needed//4
    rem = needed%4
    for i in range(nine):
        print(9,end='')

    if rem>0:
        maxi = -1
        res = -1
        for i in range(10):
            temp = '000' + bin(i)[2:]
            temp = temp[-4:]

            if int(temp[:rem])>maxi:
                maxi = int(temp[:rem])
                res = i

        print(res,end='')
    print()


for I in range(int(input())):
    n = int(input())
    needed = (n*4)-n
    nine = needed//4
    rem = needed%4

    result = nine*'9'

    '''
    if rem>0:
        maxi = -1
        res = -1
        for i in range(10):
            temp = '000' + bin(i)[2:]
            temp = temp[-4:]

            if int(temp[:rem])>maxi:
                maxi = int(temp[:rem])
                res = i

        result+=str(res)
    '''

    for i in range(n-len(result)):
        result+='8'

    print(result)


for I in range(int(input())):
    n = int(input())
    needed = (n*4)-n
    nine = needed//4
    rem = needed%4

    for i in range(nine):
        print(9,end='')

    for i in range(n-nine):
        print(8,end='')

    print()


import math
ceil = math.ceil
t = int(input())
for x in range(t):
    n0 = int(input())
    number = (n0-1)//4+1
    print("9"*(n0-number)+"8"*(number))


t = int(input())
for x in range(t):
    n = int(input())
    print("9"*(n-1)+"8")


import math
ceil = math.ceil
t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    n2 = n
    n2 = [int(x) for x in list(str(n2))]

    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    targ = n1[:-n0]

    lowest = n-2**(n0)
    #print(lowest)
    k = list(str(lowest))
    k.reverse()
    #print(k)
    while i<len(k) and k[i]=="9":
        i+=1
    #print(magic)
    i = len(k)-i

    while i>0:
        #print(lowest)
        if list("".join([bin(int(x))[2:] for x in list(str(lowest))]))[:-n0]==targ:
            break
        lowest = int("9"*(n0-i)+"8"*i)
        i-=1

    print(lowest)


t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    #print(bin(n)[2:-11])
    #print(n)
    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    #print(n1)

    i=0
    while i<n0:
        if n1[-1-i]=="1":
            #print(2**i)
            n-=2**(i)
        i+=1

    print(n)
    #print(bin(n)[2:-11])


t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    n2 = n
    n2 = [int(x) for x in list(str(n2))]

    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    targ = n1[:-n0]
    lowest = max(0, n-10)
    while lowest<n:
        if list("".join([bin(int(x))[2:] for x in list(str(lowest))]))[:-n0]==targ:
            break
        lowest+=1

    print(lowest)


t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    n2 = n
    n2 = [int(x) for x in list(str(n2))]

    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    targ = n1[:-n0]
    lowest = max(0,n-10)
    while lowest<n:
        lowest+=1
        if list("".join([bin(int(x))[2:] for x in list(str(lowest))]))[:-n0]==targ:
            break
    print(lowest)


t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    n2 = n
    n2 = [int(x) for x in list(str(n2))]

    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    targ = n1[:-n0]

    lowest = max(0, n-2**n0)

    while lowest<=n:
        #print(lowest)
        if list("".join([bin(int(x))[2:] for x in list(str(lowest))]))[:-n0]==targ:
            break
        lowest+=1

    print(lowest)


import math
ceil = math.ceil
t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    n2 = n
    n2 = [int(x) for x in list(str(n2))]

    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    targ = n1[:-n0]

    lowest = n-2**(n0)
    #print(lowest)
    k = list(str(lowest))
    k.reverse()
    #print(k)
    i=0
    while i<len(k) and k[i]=="9":
        i+=1
    #print(magic)
    i = len(k)-i

    while i>0:
        #print(lowest)
        if list("".join([bin(int(x))[2:] for x in list(str(lowest))]))[:-n0]==targ:
            break
        lowest = int("9"*(n0-i)+"8"*i)
        i-=1

    print(lowest)


import math
ceil = math.ceil
t = int(input())
for x in range(t):
    n0 = int(input())
    n = 10**n0-1
    n2 = n
    n2 = [int(x) for x in list(str(n2))]

    n1 = list("".join([bin(int(x))[2:] for x in list(str(n))]))
    targ = n1[:-n0]

    lowest = n-2**(n0)
    k = list(str(lowest))
    k.reverse()
    #print(k)
    magic=1
    if "9" in k:
        magic = k.index("9")
    #print(magic)
    i=0
    thingo = int("9"*(n0))
    i=magic
    while i>0:

        if list("".join([bin(int(x))[2:] for x in list(str(lowest))]))[:-n0]==targ:
            break

        lowest = int("9"*(n0-i)+"8"*i)
        i-=1

    print(lowest)


for _ in range(int(input())):
    n = int(input())
    x = [9]*n
    y = "".join(x)
    y = int(y)
    y = y-1
    print(y)


for _ in range(int(input())):
    n = int(input())
    x = ['9']*n
    y = "".join(x)
    y = int(y)
    y = y-1
    print(y)


import math
for _ in range(int(input())):
    n = int(input())
    x = math.ceil(n/4)
    for i in range(n-x):
        print(9 , end="")
    for j in range(x):
        print(8 , end="")
    print()


t = int(input())
for _ in range(t):
    n = int(input())
    s=""
    for i in range(n):
        s = s + "1001"
    ans = ""
    for i in range(0, 3*n, 4):
        if(i <= 3*n-4):
            ans = ans + "9"
        else:
            ans = ans + "8"
    if(len(ans) != n):
        ans = ans + '0'
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    s=""
    for i in range(n):
        s = s + "1001"
    ans = ""
    for i in range(0, 3*n, 4):
        if(i <= 3*n-4):
            ans = ans + "9"
        else:
            ans = ans + "8"
    if(len(ans) != n):
        ans = ans + '8'
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    s=""
    for i in range(n):
        s = s + "1001"
    ans = ""
    for i in range(0, 3*n, 4):
        if(i <= 3*n-4):
            ans = ans + "9"
    while(len(ans) != n):
        ans = ans + '8'
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    ans = "9"*((3*n)//4)
    ans = ans + '8'*(n-len(ans))
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    s=""
    for i in range(n):
        s = s + "1001"
    ans = ""
    for i in range(0, 3*n, 4):
        if(i < 3*n-4):
            ans = ans + "9"
        else:
            ans = ans + "8"
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    ans = "9"*((3*n)//4)
    while(len(ans) != n):
        ans = ans + '8'
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    s=""
    for i in range(n):
        s = s + "1001"
    ans = ""
    for i in range(0, 3*n, 4):
        if(i <= 3*n-4):
            ans = ans + "9"
        else:
            ans = ans + "8"
    print(ans)


t = int(input())
for i in range(t):
    n = int(input())
    s = ""
    if n == 1:
        a = bin(9)[2:-1]
        b = bin(8)[2:-1]
        if a == b:
            print(8)
        else:
            print(9)

    else:
        for i in range(n-1):
            s = s + "9"
        s = s + "8"
    print(s)


t = int(input())
for i in range(t):
    n = int(input())
    s = '9' * n
    if(n % 4 == 0):
        d = n //4
    else:
        d = (n//4) + 1
    m8 = '8 ' * d
    s = s[:n-d] + m8
    print(s)


t = int(input())
for i in range(t):
    n = int(input())
    s = '9' * n
    if(n % 4 == 0):
        d = n //4
    else:
        d = (n//4) + 1
    m8 = '8' * d
    s = s[:n-d] + m8
    print(s)


t = int(input())
for i in range(t):
    n = int(input())
    if(n % 4 == 0):
        d = n //4
    else:
        d = (n//4) + 1
    m8 = '8' * d
    s = '9' * (n-d)
    s = s + m8
    print(s)


import math
for _ in range(int(input())):
    b=list(map(int,input().split()))
    print('9'*math.ceil(b[0]-b[0]/4-1)+'8'*math.ceil(b[0]/4))


import math
for _ in range(int(input())):
    b=list(map(int,input().split()))
    x=b[0]*4
    ans=[]
    p=x-b[0]
    k=0
    while(k!=x):
       if k+4>=p:
           k=k+4
           ans.append('8')
       else:
           k=k+4
           ans.append('9')
    print(''.join(ans))


import math
for _ in range(int(input())):
    b=list(map(int,input().split()))
    x=b[0]*4
    ans=[]
    p=x-b[0]
    k=0
    while(k!=x):
       k=k+4
       if k>p:
           ans.append('8')
       else:
           ans.append('9')
    print(''.join(ans))


for _ in range(int(input())):
    b=list(map(int,input().split()))
    print('9'*(b[0]-1)+'8')


t = int(input())
for _ in range(t):
	n = int(input())
	som = ''
	for i in range(n):
		som = som+'1001'
	SOM = len(som)
	som = som[:(SOM-n)]
	for i in range(n):
		som = som+'0'
	fin = ''
	for i in range(0,(4*n),4):
		s = str(int(som[i:i+4],2))
		fin = fin+s
	print(fin)

	# for i in range(n):
	# 	x = x + '9'
	# x = int(x)
	# star = str(x)

	# while x:
	# 	x = str(x)
	# 	if (len(x)<n):
	# 		print(star)
	# 		break
	# 	the = ''
	# 	i = 0
	# 	for i in range(n):
	# 		the = the + (bin(int(x[i])).replace("0b",''))
	# 	THE = len(the)
	# 	the = the[:THE-n]
	# 	if the!=som:
	# 		print(star)
	# 		break
	# 	else:
	# 		star = x
	# 	x = int(x)
	# 	x-=1


t = int(input())
for _ in range(t):
	n = int(input())
	som = ''
	for i in range(n):
		som = som+'1001'
	SOM = len(som)
	som = som[:(SOM-n)]
	x = ''
	for i in range(n):
		x = x + '9'
	x = int(x)
	star = str(x)
	while x:
		x = str(x)
		if (len(x)<n):
			print(star)
			break
		the = ''
		i = 0
		for i in range(n):
			the = the + (bin(int(x[i])).replace("0b",''))
		THE = len(the)
		the = the[:THE-n]
		if the!=som:
			print(star)
			break
		else:
			star = x
		x = int(x)
		x-=1


t = 1
for _ in range(t):
	n = 200000
	for i in range(n - n//4 -1):
		print('9',end='')
	if n%4!=0:
		print('8',end='')
	else:
		print('9',end='')
	for i in range(n//4):
		print('8',end='')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	s = ''
	for i in range(n - n//4):
		s = s+'9'
	if n%4!=0:
		s = s[:len(s)-1]+'8'
	for i in range(n//4):
		s = s+'8'
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	som = ''
	for i in range(n):
		som = som+'1001'
	SOM = len(som)
	som = som[:(SOM-n)]
	x = ''
	for i in range(n):
		x = x + '9'
	x = int(x)
	while x:
		x = str(x)
		the = ''
		i = 0
		for i in range(n):
			the = the + (bin(int(x[i])).replace("0b",''))
		THE = len(the)
		the = the[:THE-n]
		if the!=som:
			print(star)
			break
		else:
			star = x
		x = int(x)
		x-=1


t = int(input())
for _ in range(t):
	n = int(input())
	for i in range(n - n//4 -1):
		print('9',end='')
	if n%4!=0:
		print('8',end='')
	else:
		print('9',end='')
	for i in range(n//4):
		print('8',end='')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	som = ''
	for i in range(n):
		som = som+'1001'
	SOM = len(som)
	som = som[:(SOM-n)]
	x = ''
	for i in range(n):
		x = x + '9'
	x = int(x)
	star = str(x)
	while x:
		x = str(x)
		the = ''
		i = 0
		for i in range(n):
			the = the + (bin(int(x[i])).replace("0b",''))
		THE = len(the)
		the = the[:THE-n]
		if the!=som:
			print(star)
			break
		else:
			star = x
		x = int(x)
		x-=1


t = int(input())
for _ in range(t):
	n = int(input())
	som = ''
	for i in range(n):
		som = som+'1001'
	SOM = len(som)
	som = som[:(SOM-n)]
	for i in range(n%4):
		som = som+'0'
	for i in range(n//4):
		som = som+'1000'
	fin = ''
	for i in range(0,(4*n),4):
		s = str(int(som[i:i+4],2))
		fin = fin+s
	print(fin)


import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect
from collections import deque,defaultdict,OrderedDict
import collections

def main():
    starttime=datetime.datetime.now()
    if(os.path.exists('input.txt')):
        sys.stdin = open("input.txt","r")
        sys.stdout = open("output.txt","w")

    #Solving Area Starts-->
    for _ in range(ri()):
        n=ri()
        z=(n-1)//4
        # if n%4==0:
        #     z-=1
        print("9"*(n-z-1)+"8"*(z+1))

    #<--Solving Area Ends
    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    if(os.path.exists('input.txt')):
        print("Time:",time,"ms")

class FastReader(io.IOBase):
    newlines = 0

    def __init__(self, fd, chunk_size=1024 * 8):
        self._fd = fd
        self._chunk_size = chunk_size
        self.buffer = io.BytesIO()

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self, size=-1):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

class FastWriter(io.IOBase):

    def __init__(self, fd):
        self._fd = fd
        self.buffer = io.BytesIO()
        self.write = self.buffer.write

    def flush(self):
        os.write(self._fd, self.buffer.getvalue())
        self.buffer.truncate(0), self.buffer.seek(0)

class FastStdin(io.IOBase):
    def __init__(self, fd=0):
        self.buffer = FastReader(fd)
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

class FastStdout(io.IOBase):
    def __init__(self, fd=1):
        self.buffer = FastWriter(fd)
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.flush = self.buffer.flush

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()


import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect
from collections import deque,defaultdict,OrderedDict
import collections

def main():
    starttime=datetime.datetime.now()
    if(os.path.exists('input.txt')):
        sys.stdin = open("input.txt","r")
        sys.stdout = open("output.txt","w")

    #Solving Area Starts-->
    for _ in range(ri()):
        n=ri()
        print("9"*(n-1)+"8"*(1))

    #<--Solving Area Ends
    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    if(os.path.exists('input.txt')):
        print("Time:",time,"ms")

class FastReader(io.IOBase):
    newlines = 0

    def __init__(self, fd, chunk_size=1024 * 8):
        self._fd = fd
        self._chunk_size = chunk_size
        self.buffer = io.BytesIO()

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self, size=-1):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

class FastWriter(io.IOBase):

    def __init__(self, fd):
        self._fd = fd
        self.buffer = io.BytesIO()
        self.write = self.buffer.write

    def flush(self):
        os.write(self._fd, self.buffer.getvalue())
        self.buffer.truncate(0), self.buffer.seek(0)

class FastStdin(io.IOBase):
    def __init__(self, fd=0):
        self.buffer = FastReader(fd)
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

class FastStdout(io.IOBase):
    def __init__(self, fd=1):
        self.buffer = FastWriter(fd)
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.flush = self.buffer.flush

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()


import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect
from collections import deque,defaultdict,OrderedDict
import collections

def main():
    starttime=datetime.datetime.now()
    if(os.path.exists('input.txt')):
        sys.stdin = open("input.txt","r")
        sys.stdout = open("output.txt","w")

    #Solving Area Starts-->
    for _ in range(ri()):
        n=ri()
        z=(n//4)
        print("9"*(n-z-1)+"8"*(z+1))

    #<--Solving Area Ends
    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    if(os.path.exists('input.txt')):
        print("Time:",time,"ms")

class FastReader(io.IOBase):
    newlines = 0

    def __init__(self, fd, chunk_size=1024 * 8):
        self._fd = fd
        self._chunk_size = chunk_size
        self.buffer = io.BytesIO()

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self, size=-1):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

class FastWriter(io.IOBase):

    def __init__(self, fd):
        self._fd = fd
        self.buffer = io.BytesIO()
        self.write = self.buffer.write

    def flush(self):
        os.write(self._fd, self.buffer.getvalue())
        self.buffer.truncate(0), self.buffer.seek(0)

class FastStdin(io.IOBase):
    def __init__(self, fd=0):
        self.buffer = FastReader(fd)
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

class FastStdout(io.IOBase):
    def __init__(self, fd=1):
        self.buffer = FastWriter(fd)
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.flush = self.buffer.flush

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()


import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect
from collections import deque,defaultdict,OrderedDict
import collections

def main():
    starttime=datetime.datetime.now()
    if(os.path.exists('input.txt')):
        sys.stdin = open("input.txt","r")
        sys.stdout = open("output.txt","w")

    #Solving Area Starts-->
    for _ in range(ri()):
        n=ri()
        z=(n//4)
        if n%4==0:
            z-=1
        print("9"*(n-z)+"8"*(z))

    #<--Solving Area Ends
    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    if(os.path.exists('input.txt')):
        print("Time:",time,"ms")

class FastReader(io.IOBase):
    newlines = 0

    def __init__(self, fd, chunk_size=1024 * 8):
        self._fd = fd
        self._chunk_size = chunk_size
        self.buffer = io.BytesIO()

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self, size=-1):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

class FastWriter(io.IOBase):

    def __init__(self, fd):
        self._fd = fd
        self.buffer = io.BytesIO()
        self.write = self.buffer.write

    def flush(self):
        os.write(self._fd, self.buffer.getvalue())
        self.buffer.truncate(0), self.buffer.seek(0)

class FastStdin(io.IOBase):
    def __init__(self, fd=0):
        self.buffer = FastReader(fd)
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

class FastStdout(io.IOBase):
    def __init__(self, fd=1):
        self.buffer = FastWriter(fd)
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.flush = self.buffer.flush

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()


for _ in range(int(input())):
    n= int(input())
    if(n==1):
        print("8")
    else:
        m=n%4
        r=int(n/4)
        a=n-r
        ans="8"
        for i in range(a-1):
            ans="9"+ ans
        for i in range(r):
            ans=ans+"8"
        print(ans)


for _ in range(int(input())):
    n= int(input())
    if(n==1):
        print("8")
    else:
        m=n%4
        r=int(n/4)
        a=n-r
        ans="8"
        for i in range(a-1):
            ans="9"+ ans
        for i in range(r):
            ans=ans+"0"
        print(ans)


#include<bits/stdc++.h>
const int maxn = 100100;
typedef long long ll;

using std::cin;
using std::cout;
int n, q;
namespace sam {
	const int N = ::maxn * 40;
	int ls[N], rs[N], val[N], idx;

	inline void add(int & rt, int pos, int l = 1, int r = n) {
		if(!rt) rt = ++ idx;
		val[rt] += 1;
		if(l == r) return ;
		int mid = l + r >> 1;
		pos <= mid ? add(ls[rt], pos, l, mid) : add(rs[rt], pos, mid + 1, r);
	}
	inline int merge(int x, int y) {
		if(!x || !y) return x | y;
		int p = ++ idx;
		val[p] = val[x] + val[y];
		ls[p] = merge(ls[x], ls[y]);
		rs[p] = merge(rs[x], rs[y]);
		return p;
	}
	inline int ask(int rt, int ql, int qr, int l = 1, int r = n) {
		if(ql <= l && r <= qr) return val[rt];
		int mid = l + r >> 1, ans = 0;
		if(ql <= mid) ans += ask(ls[rt], ql, qr, l, mid);
		if(mid < qr) ans += ask(rs[rt], ql, qr, mid + 1, r);
		return ans;
	}
	const int maxn = ::maxn << 1;
	int c[maxn][26], fa[maxn], mx[maxn], right[maxn], la = 1, tot = 1;
	inline void apd(int w, int id) {
		int p = la, now = la = ++ tot;
		mx[now] = mx[p] + 1, right[now] = id;
		for(;p && !c[p][w];p = fa[p]) c[p][w] = now;
		if(!p) fa[now] = 1;
		else {
			int q = c[p][w];
			if(mx[q] == mx[p] + 1) {
				fa[now] = q;
			} else {
				int x = ++tot;
				mx[x] = mx[p] + 1;
				memcpy(c[x], c[q], sizeof c[0]);
				fa[x] = fa[q];
				fa[q] = fa[now] = x;
				for(;p && c[p][w] == q;p = fa[p]) c[p][w] = x;
			}
		}
	}
	int head[maxn], next[maxn], rt[maxn];
	inline void dfs0(int x) {
		if(right[x]) add(rt[x], right[x]);
		for(int i = head[x];i;i = next[i]) dfs0(i), rt[x] = merge(rt[x], rt[i]);
	}
	inline void bd() {
		for(int i = 2;i <= tot;++i) next[i] = head[fa[i]], head[fa[i]] = i;
		dfs0(1);
	}
	inline int count(int ql, int qr, int x, int len) {
		return qr - ql + 1 >= len ? ask(rt[x], ql + len - 1, qr) : 0;
	}
}

struct edge {
	int to, nxt;
	char v;
} way[maxn << 1];
int h[maxn], num;
inline void link(int x, int y, char v) {
	way[++num] = {y, h[x], v}, h[x] = num;
	way[++num] = {x, h[y], v}, h[y] = num;
}
int size[maxn], son[maxn], dfn[maxn], top[maxn], tot;
int fav[maxn], dep[maxn], fa[maxn];
inline void dfs0(int x, int fa = 0) {
	size[x] = 1, dep[x] = dep[fa] + 1;
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa) {
		fav[way[i].to] = way[i].v;
		dfs0(way[i].to, x);
		size[x] += size[way[i].to];
		if(size[way[i].to] > size[son[x]]) son[x] = way[i].to;
	}
}
char s[maxn];
ll pw[maxn];
const ll mod = 4000000007;
const ll base = 1145141919810 % mod;

inline void dfs1(int x, int top, int fa = 0) {
	::fa[x] = fa;
	dfn[x] = ++ tot, ::top[x] = top;
	s[tot] = fav[x];
	if(son[x])
		dfs1(son[x], top, x);
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa && way[i].to != son[x]) {
		dfs1(way[i].to, way[i].to, x);
	}
}
char buf[maxn];
int idx, len, ans;
int x0, x1;
ll Hash[maxn];
inline void ps(char c) {
	buf[++idx] = c;
	Hash[idx] = (Hash[idx - 1] * base + c) % mod;
}
inline ll get() {
	return idx >= len ? (Hash[idx] + Hash[idx - len] * ll(mod - pw[len])) % mod : -1;
}
inline void push(int l, int r, ll h0) {
	if(l <= r) {
		ans += sam::count(l, r, x0, len);
		int i = l;
		for(;i <= r && i < l + len - 1;++i) {
			ps(s[i]);
			ans += get() == h0;
		}
		i = std::max(i, r - len + 2);
		for(;i <= r;++i) ps(s[i]);
	} else {
		ans += sam::count(r, l, x1, len);
		int i = l;
		for(;i >= r && i > l - len + 1;--i) ps(s[i]), ans += get() == h0;
		i = std::min(i, r + len - 2);
		for(;i >= r;--i) ps(s[i]);
	}
}
inline int ask(int x, int y, const char * s) {
	std::vector<std::pair<int, int>> v0, v1;
	for(;top[x] != top[y];) {
		if(dep[top[x]] > dep[top[y]]) {
			v0.emplace_back(dfn[x], dfn[top[x]]);
			x = fa[top[x]];
		} else {
			v1.emplace_back(dfn[top[y]], dfn[y]);
			y = fa[top[y]];
		}
	}
	if(dfn[x] < dfn[y]) v0.emplace_back(dfn[x] + 1, dfn[y]);
	if(dfn[x] > dfn[y]) v0.emplace_back(dfn[x], dfn[y] + 1);
	len = strlen(s);
	x0 = x1 = 1;
	idx = ans = 0;
	ll hs = 0;
	for(int i = 0;i < len;++i) x0 = sam::c[x0][s[i] - 'a'], hs = (hs * base + s[i] - 'a') % mod;
	for(int i = len - 1;i >= 0;--i) x1 = sam::c[x1][s[i] - 'a'];
	for(int i = 0;i < v0.size();++i) push(v0[i].first, v0[i].second, hs);
	for(int i = v1.size() - 1;i >= 0;--i) push(v1[i].first, v1[i].second, hs);
	return ans;
}
int main() {
	*pw = 1;
	for(int i = 1;i < maxn;++i) {
		pw[i] = pw[i - 1] * base % mod;
	}
	std::ios::sync_with_stdio(false), std::cin.tie(0);
	cin >> n;
	for(int i = 1;i < n;++i) {
		int u, v; char L;
		cin >> u >> v >> L;
		link(u, v, L - 'a');
	}
	dfs0(1);
	dfs1(1, 1);
	for(int i = 1;i <= n;++i) {
		sam::apd(s[i], i);
	}
	sam::bd();
	cin >> q;
	for(int i = 1, x, y;i <= q;++i) {
		static char s[200];
		cin >> x >> y >> s;
		cout << ask(x, y, s) << '\n';
	}
}


#include<bits/stdc++.h>
const int maxn = 100100;
typedef unsigned long long ll;

using std::cin;
using std::cout;
int n, q;
namespace sam {
	const int N = ::maxn * 40;
	int ls[N], rs[N], val[N], idx;

	inline void add(int & rt, int pos, int l = 1, int r = n) {
		if(!rt) rt = ++ idx;
		val[rt] += 1;
		if(l == r) return ;
		int mid = l + r >> 1;
		pos <= mid ? add(ls[rt], pos, l, mid) : add(rs[rt], pos, mid + 1, r);
	}
	inline int merge(int x, int y) {
		if(!x || !y) return x | y;
		int p = ++ idx;
		val[p] = val[x] + val[y];
		ls[p] = merge(ls[x], ls[y]);
		rs[p] = merge(rs[x], rs[y]);
		return p;
	}
	inline int ask(int rt, int ql, int qr, int l = 1, int r = n) {
		if(ql <= l && r <= qr) return val[rt];
		int mid = l + r >> 1, ans = 0;
		if(ql <= mid) ans += ask(ls[rt], ql, qr, l, mid);
		if(mid < qr) ans += ask(rs[rt], ql, qr, mid + 1, r);
		return ans;
	}
	const int maxn = ::maxn << 1;
	int c[maxn][26], fa[maxn], mx[maxn], right[maxn], la = 1, tot = 1;
	inline void apd(int w, int id) {
		int p = la, now = la = ++ tot;
		mx[now] = mx[p] + 1, right[now] = id;
		for(;p && !c[p][w];p = fa[p]) c[p][w] = now;
		if(!p) fa[now] = 1;
		else {
			int q = c[p][w];
			if(mx[q] == mx[p] + 1) {
				fa[now] = q;
			} else {
				int x = ++tot;
				mx[x] = mx[p] + 1;
				memcpy(c[x], c[q], sizeof c[0]);
				fa[x] = fa[q];
				fa[q] = fa[now] = x;
				for(;p && c[p][w] == q;p = fa[p]) c[p][w] = x;
			}
		}
	}
	int head[maxn], next[maxn], rt[maxn];
	inline void dfs0(int x) {
		if(right[x]) add(rt[x], right[x]);
		for(int i = head[x];i;i = next[i]) dfs0(i), rt[x] = merge(rt[x], rt[i]);
	}
	inline void bd() {
		for(int i = 2;i <= tot;++i) next[i] = head[fa[i]], head[fa[i]] = i;
		dfs0(1);
	}
	inline int count(int ql, int qr, int x, int len) {
		return qr - ql + 1 >= len ? ask(rt[x], ql + len - 1, qr) : 0;
	}
}

struct edge {
	int to, nxt;
	char v;
} way[maxn << 1];
int h[maxn], num;
inline void link(int x, int y, char v) {
	way[++num] = {y, h[x], v}, h[x] = num;
	way[++num] = {x, h[y], v}, h[y] = num;
}
int size[maxn], son[maxn], dfn[maxn], top[maxn], tot;
int fav[maxn], dep[maxn], fa[maxn];
inline void dfs0(int x, int fa = 0) {
	size[x] = 1, dep[x] = dep[fa] + 1;
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa) {
		fav[way[i].to] = way[i].v;
		dfs0(way[i].to, x);
		size[x] += size[way[i].to];
		if(size[way[i].to] > size[son[x]]) son[x] = way[i].to;
	}
}
char s[maxn];
ll pw[maxn];
const ll mod = 4000000007;
const ll base = 1145141919810 % mod;

inline void dfs1(int x, int top, int fa = 0) {
	::fa[x] = fa;
	dfn[x] = ++ tot, ::top[x] = top;
	s[tot] = fav[x];
	if(son[x])
		dfs1(son[x], top, x);
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa && way[i].to != son[x]) {
		dfs1(way[i].to, way[i].to, x);
	}
}
char buf[maxn];
int idx, len, ans;
int x0, x1;
ll Hash[maxn];
inline void ps(char c) {
	buf[++idx] = c;
	Hash[idx] = (Hash[idx - 1] * base + c) % mod;
}
inline ll get() {
	return idx >= len ? (Hash[idx] + Hash[idx - len] * ll(mod - pw[len])) % mod : -1;
}
inline void push(int l, int r, ll h0) {
	if(l <= r) {
		ans += sam::count(l, r, x0, len);
		int i = l;
		for(;i <= r && i < l + len - 1;++i) {
			ps(s[i]);
			ans += get() == h0;
		}
		i = std::max(i, r - len + 2);
		for(;i <= r;++i) ps(s[i]);
	} else {
		ans += sam::count(r, l, x1, len);
		int i = l;
		for(;i >= r && i > l - len + 1;--i) ps(s[i]), ans += get() == h0;
		i = std::min(i, r + len - 2);
		for(;i >= r;--i) ps(s[i]);
	}
}
inline int ask(int x, int y, const char * s) {
	std::vector<std::pair<int, int>> v0, v1;
	for(;top[x] != top[y];) {
		if(dep[top[x]] > dep[top[y]]) {
			v0.emplace_back(dfn[x], dfn[top[x]]);
			x = fa[top[x]];
		} else {
			v1.emplace_back(dfn[top[y]], dfn[y]);
			y = fa[top[y]];
		}
	}
	if(dfn[x] < dfn[y]) v0.emplace_back(dfn[x] + 1, dfn[y]);
	if(dfn[x] > dfn[y]) v0.emplace_back(dfn[x], dfn[y] + 1);
	len = strlen(s);
	x0 = x1 = 1;
	idx = ans = 0;
	ll hs = 0;
	for(int i = 0;i < len;++i) x0 = sam::c[x0][s[i] - 'a'], hs = (hs * base + s[i] - 'a') % mod;
	for(int i = len - 1;i >= 0;--i) x1 = sam::c[x1][s[i] - 'a'];
	for(int i = 0;i < v0.size();++i) push(v0[i].first, v0[i].second, hs);
	for(int i = v1.size() - 1;i >= 0;--i) push(v1[i].first, v1[i].second, hs);
	return ans;
}
int main() {
	*pw = 1;
	for(int i = 1;i < maxn;++i) {
		pw[i] = pw[i - 1] * base % mod;
	}
	std::ios::sync_with_stdio(false), std::cin.tie(0);
	cin >> n;
	for(int i = 1;i < n;++i) {
		int u, v; char L;
		cin >> u >> v >> L;
		link(u, v, L - 'a');
	}
	dfs0(1);
	dfs1(1, 1);
	for(int i = 1;i <= n;++i) {
		sam::apd(s[i], i);
	}
	sam::bd();
	cin >> q;
	for(int i = 1, x, y;i <= q;++i) {
		static char s[200];
		cin >> x >> y >> s;
		cout << ask(x, y, s) << '\n';
	}
}


#include<bits/stdc++.h>
const int maxn = 100100;
typedef long long ll;

using std::cin;
using std::cout;
int n, q;
namespace sam {
	const int N = ::maxn * 40;
	int ls[N], rs[N], val[N], idx;

	inline void add(int & rt, int pos, int l = 1, int r = n) {
		if(!rt) rt = ++ idx;
		val[rt] += 1;
		if(l == r) return ;
		int mid = l + r >> 1;
		pos <= mid ? add(ls[rt], pos, l, mid) : add(rs[rt], pos, mid + 1, r);
	}
	inline int merge(int x, int y) {
		if(!x || !y) return x | y;
		int p = ++ idx;
		val[p] = val[x] + val[y];
		ls[p] = merge(ls[x], ls[y]);
		rs[p] = merge(rs[x], rs[y]);
		return p;
	}
	inline int ask(int rt, int ql, int qr, int l = 1, int r = n) {
		if(ql <= l && r <= qr) return val[rt];
		int mid = l + r >> 1, ans = 0;
		if(ql <= mid) ans += ask(ls[rt], ql, qr, l, mid);
		if(mid < qr) ans += ask(rs[rt], ql, qr, mid + 1, r);
		return ans;
	}
	const int maxn = ::maxn << 1;
	int c[maxn][26], fa[maxn], mx[maxn], right[maxn], la = 1, tot = 1;
	inline void apd(int w, int id) {
		int p = la, now = la = ++ tot;
		mx[now] = mx[p] + 1, right[now] = id;
		for(;p && !c[p][w];p = fa[p]) c[p][w] = now;
		if(!p) fa[now] = 1;
		else {
			int q = c[p][w];
			if(mx[q] == mx[p] + 1) {
				fa[now] = q;
			} else {
				int x = ++tot;
				mx[x] = mx[p] + 1;
				memcpy(c[x], c[q], sizeof c[0]);
				fa[x] = p;
				fa[q] = fa[now] = x;
				for(;p && c[p][w] == q;p = fa[p]) c[p][w] = x;
			}
		}
	}
	int head[maxn], next[maxn], rt[maxn];
	inline void dfs0(int x) {
		if(right[x]) add(rt[x], right[x]);
		for(int i = head[x];i;i = next[i]) dfs0(i), rt[x] = merge(rt[x], rt[i]);
	}
	inline void bd() {
		for(int i = 2;i <= tot;++i) next[i] = head[fa[i]], head[fa[i]] = i;
		dfs0(1);
	}
	inline int count(int ql, int qr, int x, int len) {
		return qr - ql + 1 >= len ? ask(rt[x], ql + len - 1, qr) : 0;
	}
}

struct edge {
	int to, nxt;
	char v;
} way[maxn << 1];
int h[maxn], num;
inline void link(int x, int y, char v) {
	way[++num] = {y, h[x], v}, h[x] = num;
	way[++num] = {x, h[y], v}, h[y] = num;
}
int size[maxn], son[maxn], dfn[maxn], top[maxn], tot;
int fav[maxn], dep[maxn], fa[maxn];
inline void dfs0(int x, int fa = 0) {
	size[x] = 1, dep[x] = dep[fa] + 1;
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa) {
		fav[way[i].to] = way[i].v;
		dfs0(way[i].to, x);
		size[x] += size[way[i].to];
		if(size[way[i].to] > size[son[x]]) son[x] = way[i].to;
	}
}
char s[maxn];
ll pw[maxn];
const ll mod = 4000000007;
const ll base = 1145141919810 % mod;

inline void dfs1(int x, int top, int fa = 0) {
	::fa[x] = fa;
	dfn[x] = ++ tot, ::top[x] = top;
	s[tot] = fav[x];
	if(son[x])
		dfs1(son[x], top, x);
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa && way[i].to != son[x]) {
		dfs1(way[i].to, way[i].to, x);
	}
}
char buf[maxn];
int idx, len, ans;
int x0, x1;
ll Hash[maxn];
inline void ps(char c) {
	buf[++idx] = c;
	Hash[idx] = (Hash[idx - 1] * base + c) % mod;
}
inline ll get() {
	return idx >= len ? (Hash[idx] + Hash[idx - len] * ll(mod - pw[len])) % mod : -1;
}
inline void push(int l, int r, ll h0) {
	if(l <= r) {
		ans += sam::count(l, r, x0, len);
		int i = l;
		for(;i <= r && i < l + len - 1;++i) {
			ps(s[i]);
			ans += get() == h0;
		}
		i = std::max(i, r - len + 2);
		for(;i <= r;++i) ps(s[i]);
	} else {
		ans += sam::count(r, l, x1, len);
		int i = l;
		for(;i >= r && i > l - len + 1;--i) ps(s[i]), ans += get() == h0;
		i = std::min(i, r + len - 2);
		for(;i >= r;--i) ps(s[i]);
	}
}
inline int ask(int x, int y, const char * s) {
	std::vector<std::pair<int, int>> v0, v1;
	for(;top[x] != top[y];) {
		if(dep[top[x]] > dep[top[y]]) {
			v0.emplace_back(dfn[x], dfn[top[x]]);
			x = fa[top[x]];
		} else {
			v1.emplace_back(dfn[top[y]], dfn[y]);
			y = fa[top[y]];
		}
	}
	if(dfn[x] < dfn[y]) v0.emplace_back(dfn[x] + 1, dfn[y]);
	if(dfn[x] > dfn[y]) v0.emplace_back(dfn[x], dfn[y] + 1);
	len = strlen(s);
	x0 = x1 = 1;
	idx = ans = 0;
	ll hs = 0;
	for(int i = 0;i < len;++i) x0 = sam::c[x0][s[i] - 'a'], hs = (hs * base + s[i] - 'a') % mod;
	for(int i = len - 1;i >= 0;--i) x1 = sam::c[x1][s[i] - 'a'];
	for(int i = 0;i < v0.size();++i) push(v0[i].first, v0[i].second, hs);
	for(int i = v1.size() - 1;i >= 0;--i) push(v1[i].first, v1[i].second, hs);
	return ans;
}
int main() {
	*pw = 1;
	for(int i = 1;i < maxn;++i) {
		pw[i] = pw[i - 1] * base % mod;
	}
	std::ios::sync_with_stdio(false), std::cin.tie(0);
	cin >> n;
	for(int i = 1;i < n;++i) {
		int u, v; char L;
		cin >> u >> v >> L;
		link(u, v, L - 'a');
	}
	dfs0(1);
	dfs1(1, 1);
	for(int i = 1;i <= n;++i) {
		sam::apd(s[i], i);
	}
	sam::bd();
	cin >> q;
	for(int i = 1, x, y;i <= q;++i) {
		static char s[200];
		cin >> x >> y >> s;
		cout << ask(x, y, s) << '\n';
	}
}


#include<bits/stdc++.h>
const int maxn = 100100;
typedef long long ll;

using std::cin;
using std::cout;
int n, q;
namespace sam {
	const int N = ::maxn * 40;
	int ls[N], rs[N], val[N], idx;

	inline void add(int & rt, int pos, int l = 1, int r = n) {
		if(!rt) rt = ++ idx;
		val[rt] += 1;
		if(l == r) return ;
		int mid = l + r >> 1;
		pos <= mid ? add(ls[rt], pos, l, mid) : add(rs[rt], pos, mid + 1, r);
	}
	inline int merge(int x, int y) {
		if(!x || !y) return x | y;
		int p = ++ idx;
		val[p] = val[x] + val[y];
		ls[p] = merge(ls[x], ls[y]);
		rs[p] = merge(rs[x], rs[y]);
		return p;
	}
	inline int ask(int rt, int ql, int qr, int l = 1, int r = n) {
		if(ql <= l && r <= qr) return val[rt];
		int mid = l + r >> 1, ans = 0;
		if(ql <= mid) ans += ask(ls[rt], ql, qr, l, mid);
		if(mid < qr) ans += ask(rs[rt], ql, qr, mid + 1, r);
		return ans;
	}
	const int maxn = ::maxn << 1;
	int c[maxn][26], fa[maxn], mx[maxn], right[maxn], la = 1, tot = 1;
	inline void apd(int w, int id) {
		int p = la, now = la = ++ tot;
		mx[now] = mx[p] + 1, right[now] = id;
		for(;p && !c[p][w];p = fa[p]) c[p][w] = now;
		if(!p) fa[now] = 1;
		else {
			int q = c[p][w];
			if(mx[q] == mx[p] + 1) {
				fa[now] = q;
			} else {
				int x = ++tot;
				mx[x] = mx[p] + 1;
				memcpy(c[x], c[q], sizeof c[0]);
				fa[x] = p;
				fa[q] = fa[now] = x;
				for(;p && c[p][w] == q;p = fa[p]) c[p][w] = x;
			}
		}
	}
	int head[maxn], next[maxn], rt[maxn];
	inline void dfs0(int x) {
		if(right[x]) add(rt[x], right[x]);
		for(int i = head[x];i;i = next[i]) dfs0(i), rt[x] = merge(rt[x], rt[i]);
	}
	inline void bd() {
		for(int i = 2;i <= tot;++i) next[i] = head[fa[i]], head[fa[i]] = i;
		dfs0(1);
	}
	inline int count(int ql, int qr, int x, int len) {
		return qr - ql + 1 >= len ? ask(rt[x], ql + len - 1, qr) : 0;
	}
}

struct edge {
	int to, nxt;
	char v;
} way[maxn << 1];
int h[maxn], num;
inline void link(int x, int y, char v) {
	way[++num] = {y, h[x], v}, h[x] = num;
	way[++num] = {x, h[y], v}, h[y] = num;
}
int size[maxn], son[maxn], dfn[maxn], top[maxn], tot;
int fav[maxn], dep[maxn], fa[maxn];
inline void dfs0(int x, int fa = 0) {
	size[x] = 1, dep[x] = dep[fa] + 1;
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa) {
		fav[way[i].to] = way[i].v;
		dfs0(way[i].to, x);
		size[x] += size[way[i].to];
		if(size[way[i].to] > size[son[x]]) son[x] = way[i].to;
	}
}
char s[maxn];
ll pw[maxn];
const ll mod = 4000000007;
const ll base = 1145141919810 % mod;

inline void dfs1(int x, int top, int fa = 0) {
	::fa[x] = fa;
	dfn[x] = ++ tot, ::top[x] = top;
	s[tot] = fav[x];
	if(son[x])
		dfs1(son[x], top, x);
	for(int i = h[x];i;i = way[i].nxt) if(way[i].to != fa && way[i].to != son[x]) {
		dfs1(way[i].to, way[i].to, x);
	}
}
char buf[maxn];
int idx, len, ans;
int x0, x1;
ll Hash[maxn];
inline void ps(char c) {
	buf[++idx] = c;
	Hash[idx] = (Hash[idx - 1] * base + c) % mod;
}
inline ll get() {
	return idx >= len ? (Hash[idx] + Hash[idx - len] * ll(mod - pw[len])) % mod : -1;
}
inline void push(int l, int r, ll h0) {
	if(l <= r) {
		ans += sam::count(l, r, x0, len);
		int i = l;
		for(;i <= r && i < l + len - 1;++i) ps(s[i]), ans += get() == h0;
		i = std::max(i, r - len + 2);
		for(;i <= r;++i) ps(s[i]);
	} else {
		ans += sam::count(r, l, x1, len);
		int i = l;
		for(;i >= r && i > l - len + 1;--i) ps(s[i]), ans += get() == h0;
		i = std::min(i, r + len - 2);
		for(;i >= r;--i) ps(s[i]);
	}
}
inline int ask(int x, int y, const char * s) {
	std::vector<std::pair<int, int>> v0, v1;
	for(;top[x] != top[y];) {
		if(dep[top[x]] > dep[top[y]]) {
			v0.emplace_back(dfn[x], dfn[top[x]]);
			x = fa[top[x]];
		} else {
			v1.emplace_back(dfn[top[y]], dfn[y]);
			y = fa[top[y]];
		}
	}
	if(dfn[x] < dfn[y]) v0.emplace_back(dfn[x] + 1, dfn[y]);
	if(dfn[x] > dfn[y]) v0.emplace_back(dfn[x], dfn[y] + 1);
	len = strlen(s);
	x0 = x1 = 1;
	ans = 0;
	ll hs = 0;
	for(int i = 0;i < len;++i) x0 = sam::c[x0][s[i] - 'a'], hs = (hs * base + s[i] - 'a') % mod;
	for(int i = len - 1;i >= 0;--i) x1 = sam::c[x1][s[i] - 'a'];
	for(int i = 0;i < v0.size();++i) push(v0[i].first, v0[i].second, hs);
	for(int i = v1.size() - 1;i >= 0;--i) push(v1[i].first, v1[i].second, hs);
	return ans;
}
int main() {
	*pw = 1;
	for(int i = 1;i < maxn;++i) {
		pw[i] = pw[i] * base % mod;
	}
	std::ios::sync_with_stdio(false), std::cin.tie(0);
	cin >> n;
	for(int i = 1;i < n;++i) {
		int u, v; char L;
		cin >> u >> v >> L;
		link(u, v, L - 'a');
	}
	dfs0(1);
	dfs1(1, 1);
	for(int i = 1;i <= n;++i) {
		sam::apd(s[i], i);
	}
	sam::bd();
	cin >> q;
	for(int i = 1, x, y;i <= q;++i) {
		static char s[200];
		cin >> x >> y >> s;
		cout << ask(x, y, s) << '\n';
	}
}