/**
 * "PolandBall and Polygon"
 * http://codeforces.com/contest/755/problem/D
 * @author Ariana Herbst
 * January 15, 2017
 */
import java.util.*;
import java.io.*;

import static java.lang.Math.*;

public class VentureCupD {
    static StringBuilder sb;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int N = sc.nextInt();
        int K = sc.nextInt();
        if (K > N / 2)
        {
            K = N - K;
        }
        SegmentTree tree = buildTree(1, N);
        sb = new StringBuilder();

        int start = 1;
        int end  = 1 + K;
        boolean endNext = false;
        int count = 1;
        while (true)    {
            count++;
            int i = start + 1;
            if (i > N)  {
                i -= N;
            }
            int j = end + K - 1;
            if (j > N)  {
                j -= N;
            }
            if (j < i)
            {
                count += tree.getVal(i , N);
                count += tree.getVal(1, j);
            }
            else {
                //System.out.println("i = " + i + ", j = " + j);
                count += tree.getVal(i, j);
            }
            sb.append(count + " ");
            tree.addVal(end);
          //  System.out.println("val added, start = " + start + ", end = " + end);
            start = end;
            end = end + K;
            if (end > N)
                end -= N;
            if (endNext)
            {
                System.out.print(sb);
                System.exit(0);
            }
            if (end == 1) {
                endNext = true;
            }

        }

    }

    public static class SegmentTree {
        ArrayList<SegmentTree> children = new ArrayList();
        int a, b;
        int val;
        SegmentTree parent = null;
        public SegmentTree(int a, int b)    {
            this.a = a; this.b = b;
            val = 0;
        }
        public int getVal(int x, int y)
        {
           // System.out.println(x + " " + y + " " + a + " " + b);
            if (x <= a && y >= b)
            {
               // System.out.println("return: " + val);
                return val;
            }
            int newVal = 0;
            if ((y >= a) && (y <= b) || (x <= b) && (x >= a))
            {
                newVal += children.get(0).getVal(x, y);
                newVal += children.get(1).getVal(x, y);
            }
            return newVal;
        }
        public void addVal(int end) {
            val++;
            if (end <= b && end >= a && a != b)
            {
                if (end <= (a + b) / 2)
                {
                    children.get(0).addVal(end);
                }
                else
                {
                    children.get(1).addVal(end);
                }
            }
        }
        public void addChild(SegmentTree child)
        {
            children.add(child);
        }
    }

    public static SegmentTree buildTree(int a, int b)
    {
        SegmentTree tree = new SegmentTree(a, b);
        if (a != b)
        {
            SegmentTree childa = buildTree(a, (a + b) / 2);
            tree.addChild(childa);
            childa.parent = tree;
            SegmentTree childb = buildTree((a + b) /2 + 1, b );
            tree.addChild(childb);
            childb.parent = tree;
        }
        return tree;
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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

        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }

        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}


/**
 * "PolandBall and Polygon"
 * http://codeforces.com/contest/755/problem/D
 * @author Ariana Herbst
 * January 15, 2017
 */
import java.util.*;
import java.io.*;

import static java.lang.Math.*;

public class VentureCupD {
    static StringBuilder sb;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int N = sc.nextInt();
        int K = sc.nextInt();
        SegmentTree tree = buildTree(1, N);
        sb = new StringBuilder();

        int start = 1;
        int end  = 1 + K;
        boolean endNext = false;
        int count = 1;
        while (true)    {
            count++;
            int i = start + 1;
            if (i > N)  {
                i -= N;
            }
            int j = end + K - 1;
            if (j > N)  {
                j -= N;
            }
            if (j < i)
            {
                count += tree.getVal(i , N);
                count += tree.getVal(1, j);
            }
            else {
                //System.out.println("i = " + i + ", j = " + j);
                count += tree.getVal(i, j);
            }
            sb.append(count + " ");
            tree.addVal(end);
          //  System.out.println("val added, start = " + start + ", end = " + end);
            start = end;
            end = end + K;
            if (end > N)
                end -= N;
            if (endNext)
            {
                System.out.print(sb);
                System.exit(0);
            }
            if (end == 1) {
                endNext = true;
            }

        }

    }

    public static class SegmentTree {
        ArrayList<SegmentTree> children = new ArrayList();
        int a, b;
        int val;
        SegmentTree parent = null;
        public SegmentTree(int a, int b)    {
            this.a = a; this.b = b;
            val = 0;
        }
        public int getVal(int x, int y)
        {
           // System.out.println(x + " " + y + " " + a + " " + b);
            if (x <= a && y >= b)
            {
               // System.out.println("return: " + val);
                return val;
            }
            int newVal = 0;
            if ((y >= a) && (y <= b) || (x <= b) && (x >= a))
            {
                newVal += children.get(0).getVal(x, y);
                newVal += children.get(1).getVal(x, y);
            }
            return newVal;
        }
        public void addVal(int end) {
            val++;
            if (end <= b && end >= a && a != b)
            {
                if (end <= (a + b) / 2)
                {
                    children.get(0).addVal(end);
                }
                else
                {
                    children.get(1).addVal(end);
                }
            }
        }
        public void addChild(SegmentTree child)
        {
            children.add(child);
        }
    }

    public static SegmentTree buildTree(int a, int b)
    {
        SegmentTree tree = new SegmentTree(a, b);
        if (a != b)
        {
            SegmentTree childa = buildTree(a, (a + b) / 2);
            tree.addChild(childa);
            childa.parent = tree;
            SegmentTree childb = buildTree((a + b) /2 + 1, b );
            tree.addChild(childb);
            childb.parent = tree;
        }
        return tree;
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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

        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }

        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}


/**
 * "PolandBall and Polygon"
 * http://codeforces.com/contest/755/problem/D
 * @author Ariana Herbst
 * January 15, 2017
 */
import java.util.*;
import java.io.*;

import static java.lang.Math.*;

public class VentureCupD {
    static StringBuilder sb;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int N = sc.nextInt();
        int K = sc.nextInt();
        if (K > N / 2)
        {
            K = N - K;
        }
        SegmentTree tree = buildTree(1, N);
        sb = new StringBuilder();

        int start = 1;
        int end  = 1 + K;
        boolean endNext = false;
        long count = 1;
        while (true)    {
            count++;
            int i = start + 1;
            if (i > N)  {
                i -= N;
            }
            int j = end + K - 1;
            if (j > N)  {
                j -= N;
            }
            if (j < i)
            {
                count += tree.getVal(i , N);
                count += tree.getVal(1, j);
            }
            else {
                count += tree.getVal(i, j);
            }
            if(sb.length() > 10000){
                System.out.print(sb);
                sb = new StringBuilder();
            }
            sb.append(count + " ");
            tree.addVal(end);
            start = end;
            end = end + K;
            if (end > N)
                end -= N;
            if (endNext)
            {
                System.out.print(sb);
                System.exit(0);
            }
            if (end == 1) {
                endNext = true;
            }

        }

    }

    public static class SegmentTree {
        ArrayList<SegmentTree> children = new ArrayList(2);
        int a, b;
        int val;
        SegmentTree parent = null;
        public SegmentTree(int a, int b)    {
            this.a = a; this.b = b;
            val = 0;
        }
        public int getVal(int x, int y)
        {
            if (x <= a && y >= b)
            {
                return val;
            }
            int newVal = 0;
            if ((y >= a) && (y <= b) || (x <= b) && (x >= a))
            {
                newVal += children.get(0).getVal(x, y);
                newVal += children.get(1).getVal(x, y);
            }
            return newVal;
        }
        public void addVal(int end) {
            val++;
            if (end <= b && end >= a && a != b)
            {
                if (end <= (a + b) / 2)
                {
                    children.get(0).addVal(end);
                }
                else
                {
                    children.get(1).addVal(end);
                }
            }
        }
        public void addChild(SegmentTree child)
        {
            children.add(child);
        }
    }

    public static SegmentTree buildTree(int a, int b)
    {
        SegmentTree tree = new SegmentTree(a, b);
        if (a != b)
        {
            SegmentTree childa = buildTree(a, (a + b) / 2);
            tree.addChild(childa);
            childa.parent = tree;
            SegmentTree childb = buildTree((a + b) /2 + 1, b );
            tree.addChild(childb);
            childb.parent = tree;
        }
        return tree;
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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

        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }

        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}


    var s = readline().split(' ');
    var n = +s[0], k = +s[1];
    if (k>n/2)k = n - k;
    var x = 0, ans = [], t = [];
    for (var i=0; i<n; i++)
        t[i] = 0;
    function _get(r){
        var result = 0;
	for (; r >= 0; r = (r & (r+1)) - 1)
            result += t[r];
	return result;
    }
    function _inc(i, delta)
    {
	for (; i < n; i = (i | (i+1)))
            t[i] += delta;
    }
    function inc(from, to){
        _inc(from%n, 1);
        _inc(to%n, 1);
    }
    function get(from, to){
        from = from%n;
        to = to%n;
        if (to<from)
            return get(0, to)+get(from, n-1);
        return _get(to)-_get(from-1);
    }
    cur = 2;
    for (var i=0; i<n; i++)
    {
        inc(x, x+k);
        x = (x + k)%n;
        ans.push(cur);
        cur += get(x+1, x+k-1)+1;
    }
    print(ans.join(' '));


    var s = readline().split(' ');
    var n = +s[0], k = +s[1];
    var x = 0, ans = [], t = [];
    for (var i=0; i<n; i++)
        t[i] = 0;
    function _get(r){
        var result = 0;
	for (; r >= 0; r = (r & (r+1)) - 1)
            result += t[r];
	return result;
    }
    function _inc(i, delta)
    {
	for (; i < n; i = (i | (i+1)))
            t[i] += delta;
    }
    function inc(from, to){
        _inc(from%n, 1);
        _inc(to%n, 1);
    }
    function get(from, to){
        from = from%n;
        to = to%n;
        if (to<from)
            return get(0, to)+get(from, n-1);
        return _get(to)-_get(from-1);
    }
    cur = 2;
    for (var i=0; i<n; i++)
    {
        inc(x, x+k);
        x = (x + k);
        ans.push(cur);
        cur += get(x+1, x+k-1)+1;
    }
    print(ans.join(' '));


    var s = readline().split(' ');
    var n = +s[0], k = +s[1];
    var x = 0, ans = [], t = [];
    for (var i=0; i<n; i++)
        t[i] = 0;
    function _get(r){
        var result = 0;
	for (; r >= 0; r = (r & (r+1)) - 1)
            result += t[r];
	return result;
    }
    function _inc(i, delta)
    {
	for (; i < n; i = (i | (i+1)))
            t[i] += delta;
    }
    function inc(from, to){
        _inc(from%n, 1);
        _inc(to%n, 1);
    }
    function get(from, to){
        from = from%n;
        to = to%n;
        if (to<from)
            return get(0, to)+get(from, n-1);
        return _get(to)-_get(from-1);
    }
    cur = 2;
    for (var i=0; i<n; i++)
    {
        inc(x, x+k);
        x = (x + k)%n;
        ans.push(cur);
        cur += get(x+1, x+k-1)+1;
    }
    print(ans.join(' '));


var s=readline().split(' ')
var n=+s[0]
var k=+s[1]
if (k+k>n){k=n-k;}
var x=1
var res=1
var d=1
var q=[]
for (var i=0;i<n-1;i++)
{
    if (x+k<=n)
    {
        res+=d
        x+=k
        q.push(res)
    }
    else
    {
        d++
        res+=d
        d++
        x+=k
        x-=n
        q.push(res)
    }
}
q.push(n*k+1)
print(q.join(' '))


#include<cstdio>//cf ps 755d
#include<cstring>
using namespace std;
const int N=1e6+10;
int sum[N*3],ans=0;
void ask(int o,int l,int r,int x,int y){
	if(x<=l&&r<=y){ans+=sum[o];return;}
	int mid=(l+r)/2;
	if(x<=mid)ask(o*2,l,mid,x,y);
	if(y>mid)ask(o*2+1,mid+1,r,x,y);
}
void add(int o,int l,int r,int i){
	if(l==r){sum[o]+=1;return;}
	int mid=(l+r)/2;
	if(i<=mid)add(o*2,l,mid,i);
	else add(o*2+1,mid+1,r,i);
	sum[o]=sum[o*2]+sum[o*2+1];
}
int main()
{
	//freopen("a.in","r",stdin);
	int n,k;
	scanf("%d%d",&n,&k);long long lj=1;int g=0;
	for(int i=0;i<=3*n;i++)sum[i]=0;
	if(k<=n/2){
		for(int i=1;g<n;g++){
			int ll=i+1,rr=i+k-1;
			if(ll>n)ll=1;if(rr>n)rr-=n;ans=0;
			if(ll>rr){ask(1,1,n,ll,n);ask(1,1,n,1,rr);}
			else ask(1,1,n,ll,rr);
			printf("%lld ",(lj=lj+ans+1));
			add(1,1,n,i);
			i+=k;if(i>n)i=i-n;add(1,1,n,i);
		}
	}
	else{
		for(int i=1;g<n;g++){
			int ll=i+k+1,rr=i-1;
			if(ll>n)ll-=n;if(rr>n)rr-=n;
			ans=0;
			if(ll>rr){ask(1,1,n,ll,n);ask(1,1,n,1,rr);}
			else ask(1,1,n,ll,rr);
			printf("%lld ",(lj=lj+ans+1));
			add(1,1,n,i);
			i+=k;if(i>n)i-=n;add(1,1,n,i);
		}
	}
	putchar('\n');
	return 0;
}


#include<cstdio>//cf ps 755d
#include<cstring>
using namespace std;
const int N=1e6+10;
int sum[N*3],ans=0;
void ask(int o,int l,int r,int x,int y){
	if(x<=l&&r<=y){ans+=sum[o];return;}
	int mid=(l+r)/2;
	if(x<=mid)ask(o*2,l,mid,x,y);
	if(y>mid)ask(o*2+1,mid+1,r,x,y);
}
void add(int o,int l,int r,int i){
	if(l==r){sum[o]+=1;return;}
	int mid=(l+r)/2;
	if(i<=mid)add(o*2,l,mid,i);
	else add(o*2+1,mid+1,r,i);
	sum[o]=sum[o*2]+sum[o*2+1];
}
int main()
{
	//freopen("a.in","r",stdin);
	int n,k;
	scanf("%d%d",&n,&k);int lj=1,g=0;
	for(int i=0;i<=3*n;i++)sum[i]=0;
	for(int i=1;g<n;g++){
		int ll=i+1,rr=i+k-1;
		if(ll>n)ll=1;if(rr>n)rr-=n;ans=0;
		if(ll>rr){ask(1,1,n,ll,n);ask(1,1,n,1,rr);}
		else ask(1,1,n,ll,rr);
		printf("%d\n",(lj=lj+ans+1));
		add(1,1,n,i);
		i+=k;if(i>n)i=i-n;add(1,1,n,i);
	}
	return 0;
}


#include<cstdio>//cf ps 755d
#include<cstring>
using namespace std;
const int N=1e6+10;
int sum[N*3],ans=0;
void ask(int o,int l,int r,int x,int y){
	if(x<=l&&r<=y){ans+=sum[o];return;}
	int mid=(l+r)/2;
	if(x<=mid)ask(o*2,l,mid,x,y);
	if(y>mid)ask(o*2+1,mid+1,r,x,y);
}
void add(int o,int l,int r,int i){
	if(l==r){sum[o]+=1;return;}
	int mid=(l+r)/2;
	if(i<=mid)add(o*2,l,mid,i);
	else add(o*2+1,mid+1,r,i);
	sum[o]=sum[o*2]+sum[o*2+1];
}
int main()
{
	//freopen("a.in","r",stdin);
	int n,k;
	scanf("%d%d",&n,&k);long long lj=1;int g=0;
	for(int i=0;i<=3*n;i++)sum[i]=0;
	if(k<=n/2){
		for(int i=1;g<n;g++){
			int ll=i+1,rr=i+k-1;
			if(ll>n)ll=1;if(rr>n)rr-=n;ans=0;
			if(ll>rr){ask(1,1,n,ll,n);ask(1,1,n,1,rr);}
			else ask(1,1,n,ll,rr);
			printf("%lld ",(lj=lj+ans+1));
			add(1,1,n,i);
			i+=k;if(i>n)i=i-n;add(1,1,n,i);
		}
	}
	else{
		for(int i=1;g<n;g++){
			int ll=i+k+1,rr=i-1;
			if(ll>n)ll-=n;if(rr>n)rr-=n;if(rr==0)rr=n;
			//printf("%d %d\n",ll,rr);
			ans=0;
			if(ll>rr){ask(1,1,n,ll,n);ask(1,1,n,1,rr);}
			else ask(1,1,n,ll,rr);
			printf("%lld ",(lj=lj+ans+1));
			add(1,1,n,i);
			i+=k;if(i>n)i-=n;add(1,1,n,i);
		}
	}
	putchar('\n');
	return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=1000005;
int a[4*N];
void add(int x,int L,int R,int now)
{
    if(L>R||L>x||R<x)return;
    //printf("x=%d L=%d R=%d now=%d\n",x,L,R,now);
    a[now]++;
    if(L==x&&R==x)return;
    int mid=(L+R)>>1;
    add(x,L,mid,now<<1);
    add(x,mid+1,R,(now<<1)+1);
}
long long query(int l,int r,int L,int R,int now)
{
    if(l>r)return 0;
    //printf("l=%d r=%d L=%d R=%d now=%d\n",l,r,L,R,now);
    if(l==L&&r==R)return a[now];
    int mid=(L+R)>>1;
    if(mid>=r)return query(l,r,L,mid,now<<1);
    if(mid<l)return query(l,r,mid+1,R,(now<<1)+1);
    return query(l,mid,L,mid,now<<1)+query(mid+1,r,mid+1,R,(now<<1)+1);
}
void Solve()
{
    int n,k;
    long long ans;
    scanf("%d%d",&n,&k);
    if(k>n/2)k=n-k;
    //while(~scanf("%d%d",&n,&k))
    {
        ans=1;
        //memset(a,0,sizeof(a));
        int st=1,ed=k+1;
        for(int i=1;i<=n;i++)
        {
            if(st<ed)ans+=query(st+1,ed-1,1,n,1)+1;
            else ans+=query(st+1,n,1,n,1)+query(1,ed-1,1,n,1)+1;
            add(st,1,n,1),add(ed,1,n,1);
            st=ed,ed+=k;
            if(ed>n)ed-=n;
            //printf("%I64d%c",ans,i<n?' ':'\n');
            cout<<ans<<(i<n?' ':'\n');
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    Solve();
    return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=1000005;
int a[5*N];
void add(int x,int L,int R,int now)
{
    if(L>R||L>x||R<x)return;
    //printf("x=%d L=%d R=%d now=%d\n",x,L,R,now);
    a[now]++;
    if(L==x&&R==x)return;
    int mid=(L+R)>>1;
    add(x,L,mid,now<<1);
    add(x,mid+1,R,(now<<1)+1);
}
long long query(int l,int r,int L,int R,int now)
{
    if(l>r)return 0;
    //printf("l=%d r=%d L=%d R=%d now=%d\n",l,r,L,R,now);
    if(l==L&&r==R)return a[now];
    int mid=(L+R)>>1;
    if(mid>=r)return query(l,r,L,mid,now<<1);
    if(mid<l)return query(l,r,mid+1,R,(now<<1)+1);
    return query(l,mid,L,mid,now<<1)+query(mid+1,r,mid+1,R,(now<<1)+1);
}
void Solve()
{
    int n,k;
    long long ans;
    scanf("%d%d",&n,&k);
    //while(~scanf("%d%d",&n,&k))
    {
        ans=1;
        //memset(a,0,sizeof(a));
        int st=1,ed=k+1;
        for(int i=1;i<=n;i++)
        {
            if(st<ed)ans+=query(st+1,ed-1,1,n,1)+1;
            else ans+=query(st+1,n,1,n,1)+query(1,ed-1,1,n,1)+1;
            add(st,1,n,1),add(ed,1,n,1);
            st=ed,ed+=k;
            if(ed>n)ed-=n;
            //printf("%I64d%c",ans,i<n?' ':'\n');
            cout<<ans<<(i<n?' ':'\n');
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    Solve();
    return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=1000005;
int a[5*N];
void add(int x,int L,int R,int now)
{
    if(L>R||L>x||R<x)return;
    //printf("x=%d L=%d R=%d now=%d\n",x,L,R,now);
    a[now]++;
    if(L==x&&R==x)return;
    int mid=(L+R)>>1;
    add(x,L,mid,now<<1);
    add(x,mid+1,R,(now<<1)+1);
}
long long query(int l,int r,int L,int R,int now)
{
    if(l>r)return 0;
    //printf("l=%d r=%d L=%d R=%d now=%d\n",l,r,L,R,now);
    if(l==L&&r==R)return a[now];
    int mid=(L+R)>>1;
    if(mid>=r)return query(l,r,L,mid,now<<1);
    if(mid<l)return query(l,r,mid+1,R,(now<<1)+1);
    return query(l,mid,L,mid,now<<1)+query(mid+1,r,mid+1,R,(now<<1)+1);
}
void Solve()
{
    int n,k;
    long long ans;
    scanf("%d%d",&n,&k);
    //while(~scanf("%d%d",&n,&k))
    {
        ans=1;
        //memset(a,0,sizeof(a));
        int st=1,ed=k+1;
        for(int i=1;i<=n;i++)
        {
            if(st<ed)ans+=query(st+1,ed-1,1,n,1)+1;
            else ans+=query(st+1,n,1,n,1)+query(1,ed-1,1,n,1)+1;
            add(st,1,n,1),add(ed,1,n,1);
            st=ed,ed+=k;
            if(ed>n)ed-=n;
            printf("%I64d%c",ans,i<n?' ':'\n');
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    Solve();
    return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=1000005;
int a[4*N];
void add(int x,int L,int R,int now)
{
    if(L>R||L>x||R<x)return;
    //printf("x=%d L=%d R=%d now=%d\n",x,L,R,now);
    a[now]++;
    if(L==x&&R==x)return;
    int mid=(L+R)>>1;
    add(x,L,mid,now<<1);
    add(x,mid+1,R,(now<<1)+1);
}
int query(int l,int r,int L,int R,int now)
{
    if(l>r)return 0;
    //printf("l=%d r=%d L=%d R=%d now=%d\n",l,r,L,R,now);
    if(l==L&&r==R)return a[now];
    int mid=(L+R)>>1;
    if(mid>=r)return query(l,r,L,mid,now<<1);
    if(mid<l)return query(l,r,mid+1,R,(now<<1)+1);
    return query(l,mid,L,mid,now<<1)+query(mid+1,r,mid+1,R,(now<<1)+1);
}
void Solve()
{
    int n,k;
    long long ans;
    while(~scanf("%d%d",&n,&k))
    {
        ans=1;
        memset(a,0,sizeof(a));
        int st=1,ed=k+1;
        for(int i=1;i<=n;i++)
        {
            /*printf("a[i]:");
            for(int j=1;j<=20;j++)
                printf("%d ",a[j]);
            printf("\n");
            printf("st=%d ed=%d\n",st,ed);*/
            if(st<ed)ans+=query(st+1,ed-1,1,n,1)+1;
            else ans+=query(st+1,n,1,n,1)+query(1,ed-1,1,n,1)+1;
            add(st,1,n,1),add(ed,1,n,1);
            st=ed,ed+=k;
            if(ed>n)ed-=n;
            printf("%I64d%c",ans,i<n?' ':'\n');
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    Solve();
    return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=100005;
int fa[N],ans;
int Getfather(int x)
{
    if(fa[x]==x)return x;
    fa[x]=Getfather(fa[x]);
    return fa[x];
}
void Union(int i,int j)
{
    int fi=Getfather(i),fj=Getfather(j);
    if(fi!=fj)
    {
        ans--;
        fa[fi]=fj;
    }
}
void Solve()
{
    int n;
    cin>>n;
    //while(~scanf("%d",&n))
    {
        ans=n;
        for(int i=1;i<=n;i++)fa[i]=i;
        for(int i=1;i<=n;i++)
        {
            int j;
            scanf("%d",&j);
            Union(i,j);
        }
        printf("%d\n",ans);
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    Solve();
    return 0;
}


#include <algorithm>
#include <functional>
#include <numeric>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <sstream>
#define INF 1000000000
#define MAX_N 100000
#define MAX_E 200000
#define MOD 1000000007
using namespace std;
typedef long long int ll;
int main() {
	int n,k;
	scanf("%d %d", &n,&k);
	ll adder=1,cur_sum=2,cur_vertex=1+k;
	for(int i=0;i<n;){
		if(i<n){
			printf("%I64d ",cur_sum);
			i++;
		}
		cur_vertex+=k;
		cur_vertex%=n;
		if(cur_vertex>1 && cur_vertex<=1+k){
			adder++;
			cur_vertex+=k;
			cur_vertex%=n;
			cur_sum+=adder;
			if(i<n){
				printf("%I64d ",cur_sum);
				i++;}
			adder++;
		}
		cur_sum+=adder;
	}
}


#include <algorithm>
#include <functional>
#include <numeric>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <sstream>
#define INF 1000000000
#define MAX_N 100000
#define MAX_E 200000
#define MOD 1000000007
using namespace std;
typedef long long int ll;
int main() {
	int n, k;
	scanf("%d %d", &n, &k);
        if(k>n/2){
            k=n-k;
        }
        ll adder = 1, cur_sum = 2, cur_vertex = 1 + k;

	for (int i = 0; i < n;) {
		if (i < n) {
			printf("%I64d ", cur_sum);
			i++;
		}
		cur_vertex += k;
		cur_vertex %= n;
		if (cur_vertex > 1 && cur_vertex <= 1 + k) {
			adder++;
			cur_vertex += k;
			cur_vertex %= n;
			cur_sum += adder;
			if (i < n) {
				printf("%I64d ", cur_sum);
				i++;
			}
			adder++;
		}
		cur_sum += adder;
	}
printf("\n");
}


for _ in range(int(input())):
    n=int(input())
    ind=s=0
    lists=list(map(int,input().split()))
    for i in range(1,n):
        if(lists[i]*lists[i-1]<0):
            s+=max(lists[ind:i])
            ind=i
    l=lists[ind:]
    if(len(l)>0):
        print(max(l)+s)
    else:
        print(s)


for _ in range(int(input())):
    n=int(input())
    li=[];s=[];ans=[]
    lists=list(map(int,input().split()))
    current=lists[0]
    s.append(current)
    for i in range(1,n):
        if(current<0):
            if(lists[i]<0):
                s.append(lists[i])
            else:
                start=i
                current=max(s)
                s=[]
                break
        if(current>0):
            if(lists[i]>0):
                s.append(lists[i])
            else:
                start=i
                current=max(s)
                s=[]
                break
    ans.append(current)
    #print("start",start)
    #for i in range(start,n):
    i=start
    while(i<=n-1):
        if(current<0):
            if(lists[i]>0):
                li.append(lists[i])
            elif(len(li)>0):
                current=max(li)
                ans.append(current)
                li=[]
                i-=1
        else:
            #print("li",i,lists[i],li,current)
            if(lists[i]<0):
                li.append(lists[i])
            elif(len(li)>0):
                current=max(li)
                #print(li,current)
                ans.append(current)
                li=[]
                i-=1
        i+=1
    if(len(li)>0):
        ans.append(max(li))
    print(sum(ans))


for i in range(int(input())):
    length = int(input())
    l = list(map(int,input().split()))
    counter,curr = 1,l[0]
    summation = 0

    for j in range(1,length):
        if (curr>0 and l[j]>0) or (curr<0 and l[j]<0):
            if curr<l[j]:
                curr=l[j]
        else:
            if summation==0:
                summation = curr+l[j]
                curr = l[j]
            else:
                curr = l[j]
                summation+=curr
    if summation==0:
        print(-1)
    else:
        print(summation)


for i in range(int(input())):
    length = int(input())
    l = list(map(int,input().split()))
    counter,curr = 1,l[0]
    summation = 0
    for j in range(1,length):
        if (curr>0 and l[j]>0) or (curr<0 and l[j]<0):
            if curr<l[j]:
                curr=l[j]
        else:
            summation+=curr
            curr = l[j]
        if j==length-1:
            summation+=curr
    print(summation)


for i in range(int(input())):
    length = int(input())
    l = list(map(int,input().split()))
#    length = len(l)
    sec = [[l[0]]]
    s = 0
    index = 0
    for j in range(1,length):
        if sec[-1][-1]<0 and l[j]<0 or sec[-1][-1]>0 and l[j]>0:
            sec[-1].append(l[j])
        else:
            s+=max(sec[-1])
            sec.append([l[j]])
    s+=max(sec[-1])
    print(s)


def foo():
    n = int(input())
    a = [int(x) for x in input().split()]

    f = [0] * n

    for i in range(n):
        for j in range(i):
            if (a[j] * a[i]) < 0 or (f[j] * f[i]) < 0:
                f[i] = f[j]
        f[i] += 1

    q = max(f)

    v = [-10**10] * q
    for i in range(n):
        v[f[i]-1] = max(a[i], v[f[i]-1])

    print(sum(v))

t = int(input())
for k in range(t):
    foo()


def foo():
    n = int(input())
    a = [int(x) for x in input().split()]
    f = [None]*n
    m = a[0]
    s = 0

    for i in range(n):
        if a[i] > 0:
            f[i] = 1
        else:
            f[i] = -1

    for i in range(1,n):
        if f[i] != f[i-1]:
            s += m
            m = a[i]
        else :
            m = max(m,a[i])

    return s+m

t = int(input())
for k in range(t):
    print(foo())


def foo():
    n = int(input())
    a = [int(x) for x in input().split()]

    f = [0] * n

    for i in range(n):
        for j in range(i):
            if (a[j] * a[i]) < 0 or (f[j] * f[i]) < 0:
                f[i] = f[j]
        f[i] += 1

    q = max(f)
    if q == n:
         return sum(a)

    v = [-10**10] * q
    for i in range(n):
        v[f[i]-1] = max(a[i], v[f[i]-1])

    return sum(v)

t = int(input())
for k in range(t):
    print(foo())


def foo():
    n = int(input())
    a = [int(x) for x in input().split()]

    f = [0] * n

    for i in range(n):
        for j in range(i):
            if (a[j] * a[i]) < 0 or (f[j] * f[i]) < 0:
                f[i] = f[j]
        f[i] += 1

    q = max(f)

    v = []
    while q > 0:
        b = []

        for i in range(n):
            if f[i] == q:
                b.append((a[i]))
        v.append(max(b))
        q -= 1

    print(sum(v))

t = int(input())

for k in range(t):
    foo()


t=int(input())
for z in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    sa=[]
    f=[]
    i=0
    s=0
    while True:
        if i==n:
            break
        if a[i]>=0:
            sa.append(a[i])
        else:
            f.append(sa)
            sa=[]
            while True:
                #print(i)

                if i==n or a[i]>=0:
                    break
                sa.append(a[i])
                #print(sa,i)
                i+=1
            f.append(sa)
            #print("kk")
            sa=[]
            i=i-1
        i+=1

    print(f)
    sl=0
    #s=0
    print(sl)
    if a[0]>0:

        for i in range(len(f)):
            #s+=max(f[i])
            for i in f:
                sl+=len(i)
    else:
        for i in range(1,len(f)):
            #s+=max(f[i])
            sl+=len(f[i])
    if n==sl:
        for i in range(len(f)):
            s+=max(f[i])
    else:
        sa.append(a[n-1])
        f.append(sa)
        for i in range(1,len(f)):
            s+=max(f[i])
    print(s)
    print("lllllllllllll")


import math
def si(a):
    if a>0:
        return 1
    elif a==0:
        return 0
    else:
        return -1

t=int(input())
for z in range(t):
    n=int(input())
    s=0
    m=[]
    a=list(map(int,input().split()))
    c=a[0]
    for i in range(1,n):
        x=si(a[i-1])
        y=si(a[i])

        if x==y:
            #(a[i-1],a[i])
            #print(c)
            c=max(a[i],a[i-1])
            #print(c)
        else:
            m.append(c)
            c=a[i]
        if i==n-1:
            m.append(c)
    #print(m)
    for i in m:
        s+=i
    print(s)
    #print("..........")


t=int(input())
for z in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    i=0
    g=[]
    sum=0
    c=a[n-1]
    if c<0:
        while i<n:
            if a[i]<0:
                g.append(a[i])
                #print(g,"-ve")
            else:
                #print(g)
                if g!=[]:
                    sum+=max(g)
                    g.clear()
                while i<n and a[i]>0:
                    g.append(a[i])
                    #print("+ve",g)
                    i+=1
                i-=1
                #print(g)
                if g!=[]:
                    sum+=max(g)
                    g.clear()
            i+=1
        #print(sum)
        if g!=[]:
            sum+=max(g)
        print(sum)
    else:
        while i<n:
            if a[i]>0:
                g.append(a[i])
            else:
                if g!=[]:
                    sum+=max(g)
                    g.clear()
                while i<n and a[i]<0:
                    g.append(a[i])
                    i+=1
                i-=1
                sum+=max(g)
                g.clear()
            i+=1
        #print(sum)
        if g!=[]:
            sum+=max(g)
        print(sum)
    #print("new test case")


T =int(input())
for _ in range(T):
    n =int(input())
    arr = [int(x) for x in input().split()]
    if arr[0]>=0:
        j=1
    else:
        j=-1
    check=arr[0]
    count=0
    for i in range(1,n):

        if j==1:
            if arr[i]>check:
                check = arr[i]
            if arr[i]<0:
                count+=check
                check=arr[i]
                j=-1
        if j==-1:
            if arr[i]>check and arr[i] < 0:
                check = arr[i]
            if arr[i]>0:
                count+=check
                check=arr[i]
                j=1
        if i==n-1:
            count+=check
    print(count)


T =int(input())
for _ in range(T):
    n =int(input())
    arr = [int(x) for x in input().split()]
    if n==1:
        print(0)
    else:
        if arr[0]>=0:
            j=1
        else:
            j=-1
        once = 0
        check=arr[0]
        count=0
        for i in range(1,n):
            print(check,count,j)
            if j==1:
                if arr[i]>check:
                    check = arr[i]
                if arr[i]<0:
                    once=1
                    count+=check
                    check=arr[i]
                    j=-1
            if j==-1:
                if arr[i]>check and arr[i] < 0:
                    check = arr[i]
                if arr[i]>0:
                    once=1
                    count+=check
                    check=arr[i]
                    j=1
            if i==n-1:
                count+=check
        if once ==0:
            print(0)
        else:
            print(count)


T =int(input())
for _ in range(T):
    n =int(input())
    arr = [int(x) for x in input().split()]
    if n==1:
        print(0)
    else:
        if arr[0]>=0:
            j=1
        else:
            j=-1
        once = 0
        check=arr[0]
        count=0
        for i in range(1,n):

            if j==1:
                if arr[i]>check:
                    check = arr[i]
                if arr[i]<0:
                    once=1
                    count+=check
                    check=arr[i]
                    j=-1
            if j==-1:
                if arr[i]>check and arr[i] < 0:
                    check = arr[i]
                if arr[i]>0:
                    once=1
                    count+=check
                    check=arr[i]
                    j=1
            if i==n-1:
                count+=check
        if once ==0:
            print(0)
        else:
            print(count)


T =int(input())
for _ in range(T):
    n =int(input())
    arr = [int(x) for x in input().split()]
    if n==1:
        print(arr[0])
    else:
        if arr[0]>=0:
            j=1
        else:
            j=-1
        check=arr[0]
        count=0
        for i in range(1,n):
            if j==1:
                if arr[i]>check:
                    check = arr[i]
                if arr[i]<0:
                    count+=check
                    check=arr[i]
                    j=-1
            if j==-1:
                if arr[i]>check and arr[i] < 0:
                    check = arr[i]
                if arr[i]>0:
                    count+=check
                    check=arr[i]
                    j=1
            if i==n-1:
                count+=check
        print(count)


def single(): return int(input())
def multiple(): return list(map(int, input().split()))

t=single()
def sign(num):
    if num>0:return 1
    return -1
for i in range(t):
    n=single()
    arr=multiple()
    summ=0
    ln=0
    i=0
    while i<n:
        curr=arr[i]
        j=i
        while (j<n and sign(arr[i])==sign(arr[j])):
            curr=max(curr, arr[j])
            j+=1
        summ+=curr
        i=j-1
        i+=1
    print(summ)


def single(): return int(input())
def multiple(): return list(map(int, input().split()))

t=single()
def sign(num):
    if num>0:return 1
    return -1
for i in range(t):
    n=single()
    arr=multiple()
    positive=0
    negative=0
    summ=0
    ln=0
    for i in range(n):
        curr=arr[i]
        j=i
        while (j<n and sign(arr[i])==sign(arr[j])):
            curr=max(curr, arr[j])
            j+=1
        summ+=curr
        i=j-1
    print(summ)


n=int(input())
for l in range(n):
    a=int(input())
    kek=input().split()
    entry=[]
    for t in range(a):
        entry.append(int(kek[t]))

    i=0
    j=0
    sum=0
    while i<a and j<a :
        if int(entry[j])*int(entry[i])>0 and j!=(a-1):
            j+=1
        elif int(entry[j])*int(entry[i])>0 and j==(a-1) :
            sum+=max(entry[i:j+1])
            break
        else:
            sum+=max(entry[i:j])
            i=j
    print(sum)


n=int(input())
for l in range(n):
    a=int(input())
    kek=input().split()
    entry=[]
    for t in range(a):
        entry.append(int(kek[t]))

    i=0
    j=1
    sum=0
    while i<a and j<a :
        if int(entry[j])*int(entry[i])>0 and j!=(a-1):
            j+=1
        elif int(entry[j])*int(entry[i])>0 and j==(a-1) :
            sum+=max(entry[i:j+1])
            break
        else:
            sum+=max(entry[i:j])
            i=j
    print(sum)


def sign(n):
    if(n>0):
        return 1
    else:
        return 0
t=int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split(" ")))
    sum=0
    c=0
    while(c<n):
        j=c
        a=[]
        while(j<n and sign(l[c])==sign(l[j])):
            a.append(l[j])
            j+=1
        sum+=max(a)
        c=j
    print(sum)


t=int(input())
for i in range(t):
    n=int(input())
    l=sorted(list(map(int,input().split(" "))))
    a=[]
    b=[]
    for i in l:
        if(i>0):
            x=l.index(i)
            a=l[:x]
            b=l[x:]
            if(len(set(a))==1 and len(set(b))==1):
                print(sum(l))
            else:
                print(a[-1]+b[-1])
            break
    else:
        print(max(l))


n = int(input())

for i in range(n):
    lena = int(input()) + 1
    arr = list(map(int, input().split()))
    arr += [arr[-1]*(-1)]

    length = 0
    final = 0
    start = 0
    cur = arr[0]
    for j in range(1, lena):
        if (cur < 0 and arr[j] > 0) or (cur > 0 and arr[j] < 0):
            tsum = max(arr[start:j])
            final += tsum
            start = j
        cur = arr[j]

    print(final)


from math import inf

n = int(input())

for i in range(n):
    lena = int(input()) + 1
    arr = list(map(int, input().split()))
    arr += [arr[-1]]

    length = 0
    final = -inf
    start = 0
    cur = arr[0]
    for j in range(1, lena):
        if (cur < 0 and arr[j] < 0) or (cur > 0 and arr[j] > 0):
            if j - start >= length:
                tsum = sum(arr[start:j])
                if tsum >= final:
                    final = tsum
                    length = j - start
                    #print(j, length)
            start = j
        cur = arr[j]

    print(final)


# your code goes here

t = int(input())
for k in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = arr[0]
	sign = 0
	s = 0
	last = 0
	for i in range(n):
		if i != 0 and ((arr[i]<0 and arr[i-1]>0) or (arr[i]>0 and arr[i-1] < 0)):
			#print(i, temp)
			s+=temp
			if i==n-1:temp=0
		if arr[i]<0:
			sign-=1
			if last >= 0:
				temp = arr[i]
			else:
				temp = max(temp, arr[i])
			last = -1
		elif i>0:
			sign+=1
			if last <= 0:
				temp = arr[i]
			else:
				temp = max(temp, arr[i])
			last = 1
	print(s+temp)


# your code goes here

t = int(input())
for k in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = arr[0]
	sign = 0
	s = 0
	last = 0
	for i in range(n):
		if i != 0 and ((arr[i]<0 and arr[i-1]>0) or (arr[i]>0 and arr[i-1] < 0)):
			s+=temp
		if arr[i]<0:
			sign-=1
			if last >= 0:
				temp = arr[i]
			else:
				temp = max(temp, arr[i])
			last = -1
		elif i>0:
			sign+=1
			if last <= 0:
				temp = arr[i]
			else:
				temp = max(temp, arr[i])
			last = 1
	print(s+temp)


t = int(input())
for k in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = arr[0]
	sign = 0
	s = 0
	last = arr[0]/abs(arr[0])
	for i in range(1,n):
		if (arr[i]<0 and arr[i-1]>0) or (arr[i]>0 and arr[i-1] < 0):
			s+=temp
		if arr[i]<0:
			if last > 0:
				temp = arr[i]
			else:
				temp = max(temp, arr[i])
			last = -1
		elif arr[i]>0:
			if last < 0:
				temp = arr[i]
			else:
				temp = max(temp, arr[i])
			last = 1
	print(s+temp)


def fun(n,l):
    prev=l[0]
    sum=[]
    for i in range(1,n):
        if prev>0 and l[i]<0:
            sum.append(prev)
            prev=l[i]
        elif prev<0 and l[i]>0:
            sum.append(prev)
            prev = l[i]
        elif prev<l[i]:
            prev=l[i]
        if i==n-1:
            sum.append(prev)
    suma=0
    for i in sum:
        suma+=i
    print(suma)

for T in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    if n>1:
        fun(n,l)
    else:
        print(l[0])


def fun(n,l):
    prev=l[0]
    sum=prev
    flag=1
    for i in range(1,n):
        if prev>0 and l[i]<0:
            sum+=l[i]
            flag=0
            prev=l[i]
        elif prev<0 and l[i]>0:
            sum += l[i]
            flag = 0
            prev = l[i]
        elif prev<l[i]:
            prev=l[i]
            if flag==1:
                sum=prev
    print(sum)

for T in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    fun(n,l)


def fun(n,l):
    prev=l[0]
    sum=[]
    for i in range(1,n):
        if prev>0 and l[i]<0:
            sum.append(prev)
            prev=l[i]
        elif prev<0 and l[i]>0:
            sum.append(prev)
            prev = l[i]
        elif prev<l[i]:
            prev=l[i]
        if i==n-1:
            sum.append(prev)
    suma=0
    for i in sum:
        suma+=i
    print(suma)

for T in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    fun(n,l)


n=int(input())
l=list(map(int,input().split()))
m=[l[0]]
s=0
for i in range(n-1):
  if l[i]*l[i+1]>0:
    m.append(l[i+1])
  else:
    s+=max(m)
    m=[l[i+1]]
s+=max(m)
print(s)


for _ in range(int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 m=[l[0]]
 s=0
 for i in range(n-1):
  if l[i]*l[i+1]>0:
    m.append(l[i+1])
  else:
    s+=max(m)
    m=[l[i+1]]
 s+=max(m)
 print(s)


for _ in range(int(input())):
	a = int(input())
	lis = list(map(int,input().split()))
	def checksi(i):
		if i > 0 :
			return ("+")
		else:
			return "-"
	i = 0
	ak = lis[0]
	summ = 0
	fag = False
	while i < a-1:
		if checksi(lis[i+1])==checksi(lis[i]):
			if checksi(lis[i])=="+":
				ak = max(ak,lis[i],lis[i+1])
			elif checksi(lis[i])=="-":
				ak = max(ak,lis[i],lis[i+1])
			if i==a-2:
				summ+=ak
		else:
			if i==a-2 and fag:
				summ += lis[-1]
				summ+= ak
			else:
				fag = True
				summ+= ak
				if i < a-1:
					ak = lis[i+1]
		i+=1
	if fag:
		print(summ)
	else:
		print(-1)


for _ in range(int(input())):
	a = int(input())
	lis = list(map(int,input().split()))
	def checksi(i):
		if i > 0 :
			return ("+")
		else:
			return "-"
	i = 0
	ak = lis[0]
	summ = 0
	fag = False
	while i < a-1:
		if checksi(lis[i+1])==checksi(lis[i]):
			if checksi(lis[i])=="+":
				ak = max(ak,lis[i],lis[i+1])
			elif checksi(lis[i])=="-":
				ak = max(ak,lis[i],lis[i+1])
			if i==a-2:
				summ+=ak
		else:
			if i==a-2:
				fag = True
				summ += lis[-1]
				summ+= ak
			else:
				fag = True
				summ+= ak
				if i < a-1:
					ak = lis[i+1]
		i+=1
	if len(lis)==1:
		print(lis[0])
	elif fag:
		print(summ)
	else:
		print((max(lis)))


t=int(input())
for _ in range(t):
    n=int(input())
    a=[int(x) for x in input().split()]
    mini=int(1e9+7)
    maxi=-int(1e9+7)
    sumi=0
    flagi=-1
    for x in a:
        if flagi==-1:
            if x<0: flagi=0; mini=x
            else: flagi=1; maxi=x
        elif flagi==0:
            if x<0: mini=min(mini,x)
            else: flagi=1; maxi=x; sumi+=mini
        else:
            if x>0: maxi=max(maxi,x)
            else: flagi=0; mini=x; sumi+=maxi
    print(sumi)


t=int(input())
for _ in range(t):
    n=int(input())
    a=[int(x) for x in input().split()]
    mini=int(1e9+7)
    maxi=-int(1e9+7)
    sumi=0
    flagi=-1
    for x in a:
        if flagi==-1:
            if x<0: flagi=0; mini=x
            else: flagi=1; maxi=x
        elif flagi==0:
            if x<0: mini=max(mini,x)
            else: flagi=1; maxi=x; sumi+=mini
        else:
            if x>0: maxi=max(maxi,x)
            else: flagi=0; mini=x; sumi+=maxi
    if flagi==0: sumi+=mini
    else: sumi+=maxi
    print(sumi)


t=int(input())
for _ in range(t):
    n=int(input())
    a=[int(x) for x in input().split()]
    mini=int(1e9+7)
    maxi=-int(1e9+7)
    sumi=0
    flagi=-1
    for x in a:
        if flagi==-1:
            if x<0: flagi=0; mini=x
            else: flagi=1; maxi=x
        elif flagi==0:
            if x<0: mini=min(mini,x)
            else: flagi=1; maxi=x; sumi+=mini
        else:
            if x>0: maxi=max(maxi,x)
            else: flagi=0; mini=x; sumi+=maxi
    if flagi==0: sumi+=mini
    else: sumi+=maxi
    print(sumi)


t=int(input())
for _ in range(t):
    n=int(input())
    a=[int(x) for x in input().split()]
    mini=int(1e9+7)
    maxi=-int(1e9+7)
    sumi=0
    flagi=-1
    for x in a:
        if flagi==-1:
            if x<0: flagi=0; mini=x
            else: flagi=1; maxi=x
        elif flagi==0:
            if x<0: mini=min(mini,x)
            else: flagi=1; maxi=x; sumi+=mini
        else:
            if x>0: maxi=max(maxi,x)
            else: flagi=0; mini=x; sumi+=maxi
    if flagi=0: sumi+=mini
    else: sumi+=maxi
    print(sumi)


t=int(input())
for i in range(t):
    n=int(input())
    a=list(map(int,input().split()))[:n]
    flag1=0
    flag2=0
    s1=0
    s2=0
    d=0
    e=0
    f=0
    g=0
    c1=0
    c2=0
    for j in range(n):
        if flag1==0 and a[j]>0:
            s1+=a[j]
            d=a[j]
            flag1=1
            c1+=1
        elif flag1==1 and a[j]>0:
            if d!=0 and d<a[j]:
                s1=s1+a[j]-d
                d=a[j]
        elif flag1==1 and a[j]<0:
            s1+=a[j]
            e=a[j]
            flag1=0
            c1+=1
        elif flag1==0 and a[j]<0:
            if e!=0 and e<a[j]:
                s1=s1+a[j]
                e*=-1
                s1+=e
                e=a[j]
        if flag2==0 and a[j]<0:
            s2+=a[j]
            f=a[j]
            flag2=1
            c2+=1
        elif flag2==1 and a[j]<0:
            if f!=0 and f<a[j]:
                s2=s2+a[j]
                f*=-1
                s2+=e
                f=a[j]
        elif flag2==1 and a[j]>0:
            s2+=a[j]
            g=a[j]
            flag2=0
            c2+=1
        elif flag2==0 and a[j]>0:
            if g!=0 and g<a[j]:
                s2+=a[j]-g
                g=a[j]
    if c1>c2:
        print(s1)
    elif c2>c1:
        print(s2)
    else:
        print(max(s1,s2))


t=int(input())
for i in range(t):
    n=int(input())
    a=list(map(int,input().split()))[:n]
    flag1=0
    flag2=0
    s1=0
    s2=0
    d=0
    e=0
    f=0
    g=0
    c1=0
    c2=0
    for j in range(n):
        if flag1==0 and a[j]>0:
            s1+=a[j]
            d=a[j]
            flag1=1
            c1+=1
        elif flag1==1 and a[j]>0:
            if d!=0 and d<a[j]:
                s1=s1+a[j]-d
                d=a[j]
        elif flag1==1 and a[j]<0:
            s1+=a[j]
            e=a[j]
            flag1=0
            c1+=1
        elif flag1==0 and a[j]<0:
            if e!=0 and e<a[j]:
                s1+=a[j]-d
                e=a[j]
        if flag2==0 and a[j]<0:
            s2+=a[j]
            f=a[j]
            flag2=1
            c2+=1
        elif flag2==1 and a[j]<0:
            if f!=0 and f<a[j]:
                s2+=a[j]-f
                f=a[j]
        elif flag2==1 and a[j]>0:
            s2+=a[j]
            g=a[j]
            flag2=0
            c2+=1
        elif flag2==0 and a[j]>0:
            if g!=0 and g<a[j]:
                s2+=a[j]-g
                g=a[j]
    if c1>c2:
        print(s1)
    elif c2>c1:
        print(s2)
    else:
        print(max(s1,s2))


t=int(input())
for i in range(t):
    n=int(input())
    a=list(map(int,input().split()))[:n]

    flag1=0
    flag2=0
    s1=0
    s2=0
    d=0
    e=0
    f=0
    g=0
    c1=0
    c2=0
    for j in range(n):
        if flag1==0 and a[j]>0:
            s1+=a[j]
            d=a[j]
            flag1=1
            c1+=1
        elif flag1==1 and a[j]>0:
            if d!=0 and d<a[j]:
                s1=s1+a[j]-d
                d=a[j]
        elif flag1==1 and a[j]<0:
            s1+=a[j]
            e=a[j]
            flag1=0
            c1+=1
        elif flag1==0 and a[j]<0:
            if e!=0 and e<a[j]:
                s1=s1+a[j]
                e*=-1
                s1+=e
                e=a[j]
        if flag2==0 and a[j]<0:
            s2+=a[j]
            f=a[j]
            flag2=1
            c2+=1
        elif flag2==1 and a[j]<0:
            if f!=0 and f<a[j]:
                s2=s2+a[j]
                f*=-1
                s2+=f
                f=a[j]
        elif flag2==1 and a[j]>0:
            s2+=a[j]
            g=a[j]
            flag2=0
            c2+=1
        elif flag2==0 and a[j]>0:
            if g!=0 and g<a[j]:
                s2+=a[j]-g
                g=a[j]
    if c1>c2:
        print(s1)
    elif c2>c1:
        print(s2)
    else:
        print(max(s1,s2))


t = int(input())

for _ in range(t):
    l = int(input())
    a = list(map(int, input().split()))
    c = 0
    m = a[0]
    for i in range(l-1):
        if a[i] * a[i+1] > 0:
            m = max(a[i], a[i+1])
        else:
            c += m
            m = a[i+1]

    c += m

    if a[-1] * m < 0:
        c += a[-1]

    print(c)


t = int(input())

for _ in range(t):
    l = int(input())
    a = list(map(int, input().split()))
    c = 0
    m = a[0]
    for i in range(l-1):
        if a[i] * a[i+1] > 0:
            m = max(m, a[i+1])
        else:
            c += m
            m = a[i+1]

    c += m

    if a[-1] * m < 0:
        c += a[-1]

    print(c)


for _ in range(int(input())):
    n = int(input())
    a = list(map(int,input().split()))
    k = 0
    max_val = -100
    sum_el = 0
    max_sum = None
    i = 0
    while i < n:
        if i == 0 or k == 0:
            sum_el = a[i]
            k += 1
            #print(i, max_val, k, sum_el, max_sum, a)

            i += 1
            continue
        if (a[i-1] > 0 and a[i] < 0) or (a[i] > 0 and a[i-1] < 0):
            sum_el += a[i]
            k += 1

        else:
            if k >= max_val:
                k = max_val
                if max_sum is None:
                    max_sum = sum_el
                else:
                    max_sum = max(max_sum,sum_el)
            sum_el = 0
            k = 0
        #print(i,max_val,k,sum_el,max_sum,a)

        i += 1
    if max_sum is None:
        print(sum_el)
    else:
        print(max_sum)


#####################################

import atexit
import io
import sys

input = sys.stdin.readline
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

    #####################################

for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    k = 0
    start = 0
    end = 0
    l = []
    if a[0] < 0:
        last = -1
    else:
        last = 1
    for i in range(1, n):
        if a[i] * last > 0:
            continue
        else:
            # print(a[start:i])
            if last == 1:
                l.append(max(a[start:i]))
                start = i
                last *= -1
            else:

                l.append(max(a[start:i]))
                start = i
                last *= -1
    # print(a[start:i + 1])
    if last == 1:
        l.append(max(a[start:n]))

    else:
        l.append(max(a[start:n]))

    print(sum(l))


for _ in range(int(input())):
    n = int(input())
    a = list(map(int,input().split()))
    k = 0
    start = 0
    end = 0
    l = []
    if a[0] < 0:
        last = -1
    else:
        last = 1
    for i in range(1,n):
        if a[i]*last > 0:
            continue
        else:
            # print(a[start:i])
            if last == 1:
                l.append(max(a[start:i]))
                start = i
                last *= -1
            else:

                l.append(max(a[start:i]))
                start = i
                last *= -1
   # print(a[start:i + 1])
    if last == 1:
        l.append(max(a[start:i + 1]))
        start = i
        last *= -1
    else:
        l.append(max(a[start:i + 1]))
        start = i
        last *= -1

    print(sum(l))


for _ in range(int(input())):
    n = int(input())
    a = list(map(int,input().split()))
    k = 0
    start = 0
    end = 0
    l = []
    if a[0] < 0:
        last = -1
    else:
        last = 1
    for i in range(1,n):
        if a[i]*last > 0:
            continue
        else:
            # print(a[start:i])
            if last == 1:
                l.append(max(a[start:i]))
                start = i
                last *= -1
            else:

                l.append(max(a[start:i]))
                start = i
                last *= -1
   # print(a[start:i + 1])
    if last == 1:
        l.append(max(a[start:n]))

    else:
        l.append(max(a[start:n]))

    print(sum(l))


for _ in range(int(input())):
  n=int(input())
  a=list(map(int,input().split()))
  total=0
  m=a[0]
  for i in range(1,n):
    if (m>0 and a[i]<0)or(m<0 and a[i]>0):
      total+=m
      m=a[i]
    else:
      m=max(m,a[i])
  print(total+m)


import itertools
for _ in range(int(input())):
  n=input()
  group=itertools.groupby(map(int,input().split()),lambda x:x<0)
  s=0
  for _,v in group:
    s+=max(list(v))
  print(s)


import itertools
for _ in range(int(input())):
  n=input()
  group=itertools.groupby(map(int,input().split()),lambda x:x<0)
  l=[]
  for _,v in group:
    l.append(max(list(v)))
  print(sum(l))


for _ in range(int(input())):
  n=int(input())
  a=list(map(int,input().split()))
  i=0
  while i<n-1:
    if a[i]*a[i+1]>0:
      if a[i]<a[i+1]:
        del a[i]
      else: del a[i+1]
      n-=1
    else:
      i+=1
  total=0
  for k in a: total+=k
  print(total)


for _ in range(int(input())):
  n=int(input())
  a=list(map(int,input().split()))
  i=0
  while i<n-1:
    if a[i]*a[i+1]>0:
      a.remove(min(a[i],a[i+1]))
      n-=1
    else:
      i+=1
  total=0
  for k in a: total+=k
  print(total)


import itertools
group=itertools.groupby(map(int,'1 2 3 -1 -2'.split()),lambda x:x<0)
l=[]
for _,v in group:
  l.append(max(list(v)))
print(sum(l))


t = int(input())
for i in range(t):
    n = int(input())
    l = list(map(int, input().split()))

    if l[0] > 0: positive = True
    else: positive = False

    ans = [l[0]]

    for i in l[1:]:
        if positive == True and i < 0:
            ans.append(i) # 使序列最長
            positive = False # 正負相間
        elif positive == True and ans[-1] < i:
            ans[-1] = i # 使 sum 最大化
        elif positive == False and i > 0:
            ans.append(i)
            positive = True
        elif positive == False and ans[-1] < i:
            ans[-1] = i
    print(sum(ans))


t = int(input())
for i in range(t):
    n = int(input())
    l = list(map(int, input().split()))
    S = 0
    a = False
    for j in range(1, n):
        if l[j] > 0:
            if l[j - 1] < 0:
                if a == False:
                    S += l[j] + l[j - 1]
                    a = True
                else:
                    S += l[j]
            else:
                continue
        else:
            if l[j - 1] > 0:
                if a == False:
                    S += l[j] + l[j - 1]
                    a = True
                else:
                    S += l[j]
            else:
                continue
    if a == False:
        print(sorted(l)[-1])
    else:
        print(S)


t = int(input())
for i in range(t):
    n = int(input())
    l = list(map(int, input().split()))

    if l[0] > 0: positive = True
    else: positive = False

    ans = [l[0]]

    for i in l[1:]:
        if positive == True and ans[-1] < i:
            ans[-1] = i # 使 sum 最大化
        elif positive == True and i < 0:
            ans.append(i) # 使序列最長
            positive = False # 正負相間
        elif positive == False and i > 0:
            ans.append(i)
            positive = True
        elif positive == False and ans[-1] < i:
            ans[-1] = i
        print(ans)
    print(sum(ans))


for _ in range(int(input())):
    n=int(input())
    a=[int(i) for i in input().split()]
    a.append(0)
    b=[]
    c=[]
    for i in range(n):
        c.append(a[i])
        if (a[i+1]>0 and a[i]>0) or (a[i+1]<0 and a[i]<0):
            c.append(a[i+1])
        else:
            b.append(max(c))
            c=[]
    print(sum(b))


for _ in range(int(input())):
    n=int(input())
    a=[int(i) for i in input().split()]
    a.append(0)
    summ=0
    c=[]
    for i in range(n):
        c.append(a[i])
        if (a[i+1]>0 and a[i]>0) or (a[i+1]<0 and a[i]<0):
            c.append(a[i+1])
        else:
            summ+=max(c)
            c=[]
    print(summ)


from math import *
for _ in range(int(input())):
    n=int(input())
    a=[int(i) for i in input().split()]
    a.append(0)
    b=[]
    c=[]
    for i in range(n):
        c.append(a[i])
        if (a[i+1]>0 and a[i]>0) or (a[i+1]<0 and a[i]<0):
            c.append(a[i+1])
        else:
            b.append(max(c))
            c=[]
    r=len(b)-1
    if r>0 and ((b[0]>0 and b[r]>0) or (b[0]<0 and b[r]<0)):
        if b[0]>b[r]:
            print(sum(b[:r]))
        else:
            print(sum(b[1:]))
    else:
        print(sum(b))


t=int(input())
print (t)
while(t>0):
    while(True):
        try:
            n=int(input())
            print(n)
            break
        except EOFError:
            continue
    d={}
    for i in range(n):
        #while(True):
           # try:
        a=input().split(' ')
                #break
           # except EOFError:
              #  continue
        length=1
        s=(int(a[0]))
        d[1]=[s]
        for j in range (1,len(a)):
            d[1].append(int(a[j]))
            if (int(a[j])*int(a[j-1])<0):
                length+=1
                s+=int(a[j])
            else:
                if length in d:
                    d[length].append(s)
                else:
                    d[length]=[s]
                s=int(a[j])
                length=1
        print (max(d[max(d.keys())]))
    t-=1


t=int(input())
while(t>0):
    n=int(input())
    d={}
    a = list(map(int,input().split()))
    length=1
    s=int(a[0])
    d[1]=[int(s)]
    for j in range (1,len(a)):
        d[1].append(int(a[j]))
        if (int(a[j])*int(a[j-1])<0):
            length+=1
            s+=int(a[j])
        else:
            if length in d:
                d[length].append(s)
            else:
                d[length]=[s]
                s=int(a[j])
                length=1
    print (max(d[max(d.keys())]))
    t-=1


t=int(input())
while(t>0):
    n=int(input())
    a = list(map(int,input().split()))
    k=a[0]
    l=[[k]]
    len(l)
    t-=1
    m=0
    for i in range(1,n):
        if((a[i]*a[i-1])>0):
            l[m].append(a[i])
        else:
            l[m+1]=[a[i]]
            m+=1
    print(l)


t=int(input())
print (t)
while(t>0):
    while(True):
        try:
            n=int(input())
            print(n)
            break
        except EOFError:
            continue
    d={}
    for i in range(n):
        #while(True):
           # try:
        a=input().split(' ')
                #break
           # except EOFError:
              #  continue
        length=1
        s=(int(a[0]))
        d[1]=[s]
        for j in range (1,len(a)):
            d[1].append(int(a[j]))
            if (int(a[j])*int(a[j-1])<0):
                length+=1
                s+=int(a[j])
            else:
                if length in d:
                    d[length].append(s)
                else:
                    d[length]=[s]
                s=int(a[j])
                length=1
        print (max(d[max(d.keys())]))
        print(d)
    t-=1


t=int(input())
while(t>0):
    n=int(input())
    a=list(map(int,input().split()))
    k=a[0]
    l=[[k]]
    len(l)
    t-=1
    m=0
    for i in range(1,len(a)):
        if((a[i]*a[i-1])>0):
            try:
                l[m].append(a[i])
            except IndexError:
                print(m)
                print(i)
                print("s")
        else:
            try:
                l.append([a[i]])
            except IndexError:
                print(m)
                print(i)
                print("t")
            m+=1
    ans=0
    for i in l:
        ans+=max(i)
    print(ans)


t=int(input())
while(t>0):
    n=int(input())
    d={}
    for i in range(n):
        a=input().split(' ')
        length=1
        s=(int(a[0]))
        d[1]=[s]
        for j in range (1,len(a)):
            d[1].append(int(a[j]))
            if (int(a[j])*int(a[j-1])<0):
                length+=1
                s+=int(a[j])
            else:
                if length in d:
                    d[length].append(s)
                else:
                    d[length]=[s]
                s=int(a[j])
                length=1
        print (max(d[max(d.keys())]))
    t-=1


t=int(input())
print (t)
while(t>0):
    #while(True):
     #   try:
    n=int(input())
      #      print(n)
       #     break
        #except EOFError:
         #   continue
    d={}
    for i in range(n):
        #while(True):
           # try:
        a=input().split(' ')
                #break
           # except EOFError:
              #  continue
        length=1
        s=(int(a[0]))
        d[1]=[s]
        for j in range (1,len(a)):
            d[1].append(int(a[j]))
            if (int(a[j])*int(a[j-1])<0):
                length+=1
                s+=int(a[j])
            else:
                if length in d:
                    d[length].append(s)
                else:
                    d[length]=[s]
                s=int(a[j])
                length=1
        print (max(d[max(d.keys())]))
    t-=1


for _ in range(int(input())):
    n = int(input())
    arr = list(map(int, input().split()))
    new_seq = []
    i = 0
    j = i
    if arr[j] < 0:
        temp = []
        while j < n and arr[j] < 0:
            temp.append(arr[j])
            j += 1
        new_seq.append(max(temp))
    else:
        temp = []
        while j < n and arr[j] > 0:
            temp.append(arr[j])
            j += 1
        new_seq.append(max(temp))
    i = j
    while True:
        if new_seq[-1] < 0:
            temp = []
            while j < n and arr[j] > 0:
                temp.append(arr[j])
                j += 1
            if temp == []:
                break
            new_seq.append(max(temp))
        else:
            temp = []
            while j < n and arr[j] < 0:
                temp.append(arr[j])
                j += 1
            if temp == []:
                break
            new_seq.append(max(temp))
    print(sum(new_seq))


for _ in range(int(input())):
    n = int(input())
    arr = list(map(int, input().split()))
    new_seq = []
    i = 0
    j = i
    if arr[j] < 0:
        temp = []
        while j < n and arr[j] < 0:
            temp.append(arr[j])
            j += 1
        new_seq.append(max(temp))
    else:
        temp = []
        while j < n and arr[j] > 0:
            temp.append(arr[j])
            j += 1
        new_seq.append(max(temp))
    i = j
    while True:
        if new_seq[-1] < 0:
            temp = []
            while j < n and arr[j] > 0:
                temp.append(arr[j])
                j += 1
            if temp == []:
                break
            new_seq.append(max(temp))
        else:
            temp = []
            while j < n and arr[j] < 0:
                temp.append(arr[j])
                j += 1
            if temp == []:
                break
            new_seq.append(max(temp))
    print(new_seq)
    print(sum(new_seq))


for t in range(int(input())):
    n = int(input())
    li = list(map(int, input().split()))
    i = 0
    while i < len(li):
        if li[i] < 0:
            first = li[i]
            fp = i
            while i + 1 < len(li) and li[i + 1] < 0:
                if li[i + 1] > first:
                    first = li[i + 1]
                    li.pop(fp)
                    fp = i
                else:
                    li.pop(i + 1)
            else:
                i = i + 1
        else:
            first = li[i]
            fp = i
            while i + 1 < len(li) and li[i + 1] > 0:
                if li[i + 1] > first:
                    first = li[i + 1]
                    li.pop(fp)
                    fp = i
                else:
                    li.pop(i + 1)
            else:
                i = i + 1
    print(sum(li))


for t in range(int(input())):
    n=int(input())
    li=list(map(int,input().split()))
    total=0
    f,l=0,0
    prepos = True if li[0]>0 else False
    for i in range(1,n):
        if li[i]<0:
            if prepos:
                total=total+max(li[f:l+1])
                f = i
                l = i
            else:
                l = i
            prepos = False
        else:
            if not prepos:
                total = total + max(li[f:l+1])
                f = i
                l = i
            else:
                l = i
            prepos = True
    total = total + max(li[f:l+1])
    print(total)


for t in range(int(input())):
    n=int(input())
    li=list(map(int,input().split()))
    total=0
    temp=[]
    f,l=0,0
    prepos = True if li[0]>0 else False
    for i in range(1,n):
        if li[i]<0:
            if prepos:
                l=i
                total=total+max(li[f:i])
                f=i
            else:
                l=i
            prepos = False
        else :
            if not prepos:
                l = i
                total = total + max(li[f:i])
                f = i
            else:
                l=i
            prepos = True
    l=i+1
    total = total + max(li[f:l])
    print(total)


n=int(input())
s=[]
l=list(map(int,input().split()))
c=0
t1=[]
for i in range(n):
    if(c==2)and(l[i]>0):

        t1.append(l[s[0]]+l[s[1]])
        s=[]
        c=0
    if(s==[])and(l[i]>0):
        s.append(i)
        c+=1
    elif(c==1)and(l[i]>0):
        t=i
        while(l[s[0]]<l[t])and(l[t]>0):
            s.pop()
            s.append(i)
            t+=1
    elif(c==1)and(l[i]<0):
        s.append(i)
        c+=1
    elif(c==1)and(l[i]<0):
        t=i
        print(i)
        while(l[s[1]]<l[t])and(l[t]<0):
            s.pop()
            s.append(i)
            t+=1
if(len(s)==2):
    t1.append(l[s[0]]+l[s[1]])
if(l[n-1]>0)and(l[0]<0):
    t1.append(l[n-1]+l[0])
if(t1==[]):
    print(max(l))
else:
    print(sum(t1))


te=int(input())
for i in range(te):
    n=int(input())
    s=[]
    l=list(map(int,input().split()))
    c=0
    t1=[]
    for i in range(n):
        if(c==2)and(l[i]>0):
            t1.append(l[s[0]]+l[s[1]])
            s=[]
            c=0
        if(s==[])and(l[i]>0):
            s.append(i)
            c+=1
        elif(c==1)and(l[i]>0):
            t=i
            while(l[s[0]]<l[t])and(l[t]>0):
                s.pop()
                s.append(i)
                t+=1
        elif(c==1)and(l[i]<0):
            s.append(i)
            c+=1
        elif(c==1)and(l[i]<0):
            t=i
            print(i)
            while(l[s[1]]<l[t])and(l[t]<0):
                s.pop()
                s.append(i)
                t+=1
    if(len(s)==2):
        t1.append(l[s[0]]+l[s[1]])
    if(l[n-1]>0)and(l[0]<0):
        t1.append(l[n-1]+l[0])
    if(t1==[]):
        print(max(l))
    else:
        print(sum(t1))


t=int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    k=[]
    for i in range(n-1):
        if(l[i+1]<0)and(l[i]>0):
            k.append(l[i])
            k.append(l[i+1])
    if(l[0]<0)and(l[len(l)-1]>0):
        k.append(l[0])
        k.append(l[n-1])

    if(k==[]):
        print(max(l))
    else:
        print(sum(k))


test=int(input())
for i in range(test):
    n=int(input())
    l=list(map(int,input().split()))
    c,s2=0,0
    s=[]
    s1=[]
    for i in range(len(l)):
        if(l[i]>0):
            s.append(l[i])
            if(s1!=[]):
                q=max(s1)
                s2=s2+q
                s1=[]
        if(l[i]<0):
            s1.append(l[i])
            if(s!=[]):
                q=max(s)
                s2=s2+q
                s=[]
    if(s!=[]):
        s2=s2+max(s)
    if(s1!=[]):
        s2=s2+max(s1)
    print(s2)


t=int(input())
while t:
    t=t-1
    n=int(input())
    l=list(map(int,input().split()))
    max_ending_here=0
    lp,ln=0,0
    for i in range(n):
        if l[i]<0 and i==0:
            sign='n'
            max_ending_here+=l[i]
            ln=l[i]
        elif l[i]>0 and i==0:
            sign='p'
            max_ending_here+=l[i]
            lp=l[i]
        else:
            if sign=='n' and l[i]>0:
                max_ending_here+=l[i]
                sign='p'
                lp=l[i]
            elif sign=='n' and l[i]<0:
                if l[i]>ln:
                    max_ending_here-=ln
                    max_ending_here+=l[i]
                    ln=l[i]
            elif sign=='p' and l[i]<0:
                max_ending_here+=l[i]
                sign='n'
            elif sign=='p' and l[i]>0:
                if l[i]>lp:
                    max_ending_here-=lp
                    max_ending_here+=l[i]
                    lp=l[i]
    print(max_ending_here)


t=int(input())
while t:
    t=t-1
    n=int(input())
    l=list(map(int,input().split()))
    max_ending_here=0
    lp,ln=0,0
    for i in range(n):
        if l[i]<0 and i==0:
            sign='n'
            max_ending_here+=l[i]
            ln=l[i]
        elif l[i]>0 and i==0:
            sign='p'
            max_ending_here+=l[i]
            lp=l[i]
        else:
            if sign=='n' and l[i]>0:
                max_ending_here+=l[i]
                sign='p'
                lp=l[i]
            elif sign=='n' and l[i]<0:
                if l[i]>lp:
                    max_ending_here-=ln
                    max_ending_here+=l[i]
                    ln=l[i]
            elif sign=='p' and l[i]<0:
                max_ending_here+=l[i]
                sign='n'
            elif sign=='p' and l[i]>0:
                if l[i]>lp:
                    max_ending_here-=lp
                    max_ending_here+=l[i]
                    lp=l[i]
    print(max_ending_here)


t=int(input())
while t:
    t=t-1
    n=int(input())
    l=list(map(int,input().split()))
    max_ending_here=0
    lp,ln=0,0
    for i in range(n):
        if l[i]<0 and i==0:
            sign='n'
            max_ending_here+=l[i]
            ln=l[i]
        elif l[i]>0 and i==0:
            sign='p'
            max_ending_here+=l[i]
            lp=l[i]
        else:
            if sign=='n' and l[i]>0:
                max_ending_here+=l[i]
                sign='p'
                lp=l[i]
            elif sign=='n' and l[i]<0:
                if l[i]>ln:
                    max_ending_here-=ln
                    max_ending_here+=l[i]
                    ln=l[i]
            elif sign=='p' and l[i]<0:
                max_ending_here+=l[i]
                sign='n'
                ln=l[i]
            elif sign=='p' and l[i]>0:
                if l[i]>lp:
                    max_ending_here-=lp
                    max_ending_here+=l[i]
                    lp=l[i]
    print(max_ending_here)


t = int(input())
ans = ""
for i in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    sum,last = 0,arr[0]
    for j in range(1,n,1):
        if(arr[j]*last>0):
            last = max(last,arr[j])
        else:
            sum += last
            last = arr[j]
    sum+=last
    ans+=str(sum)+"\n"
print(ans)


t = int(input())
ans = ""
for i in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    sum,last = 0,arr.pop(0)
    while(len(arr)>0):
        a = arr.pop(0)
        if(a*last>0):
            last = max(last,a)
        else:
            sum += last
            last = a
    sum+=last
    ans+=sum+"\n"
print(ans)


t = int(input())
ans = ""
for i in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    sum,last = 0,arr.pop(0)
    while(len(arr)>0):
        a = arr.pop(0)
        if(a*last>0):
            last = max(last,a)
        else:
            sum += last
            last = a
    sum+=last
    ans+=str(sum)+"\n"
print(ans)


def sign(a,b):
    if((a>0 and b>0)or(a<0 and b<0)):
        return True
    return False

t = int(input())
for i in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    sum,last = 0,arr.pop(0)
    while(len(arr)>0):
        a = arr.pop(0)
        if(sign(a,last)):
            last = max(last,a)
        else:
            sum += last
            last = a
    sum+=last
    print(sum)


def alt_subsequence(arr, n):
    int_list = list(map(lambda x: 'P' if x>0 else 'N', arr))
    idx_list = []
    sum_list = []
    if all('P' == i for i in int_list):
        return max(arr)
    elif all('N' == i for i in int_list):
        return max(arr)
    else:
        for i in range(n-1):
            if int_list[i] == 'N' and int_list[i+1] == 'P':
                idx_list.append(i+1)
            elif int_list[i] == 'P' and int_list[i+1] == 'N':
                idx_list.append(i+1)
        for i in range(len(idx_list)-1):
            if i == 0 and idx_list[0] != 0:
                sum_list.append(max(arr[:idx_list[i]]))
            sum_list.append(max(arr[idx_list[i]:idx_list[i+1]]))
        sum_list.append(max(arr[idx_list[-1]:]))
        return sum(sum_list)

t = int(input())
for t_itr in range(t):
    n = int(input())
    arr = list(map(int, input().rstrip().split()))
    result = alt_subsequence(arr, n)

    print(result)


def alt_subsequence(arr, n):
    int_list = list(map(lambda x: 'P' if x>0 else 'N', arr))
    idx_list = []
    sum_list = []
    if all('P' == i for i in int_list):
        return max(arr)
    elif all('N' == i for i in int_list):
        return max(arr)
    else:
        for i in range(n-1):
            if int_list[i] == 'N' and int_list[i+1] == 'P':
                idx_list.append(i+1)
            elif int_list[i] == 'P' and int_list[i+1] == 'N':
                idx_list.append(i+1)
        sum_list.append(max(arr[:idx_list[0]]))
        for i in range(len(idx_list)-1):
            sum_list.append(max(arr[idx_list[i]:idx_list[i+1]]))
        sum_list.append(max(arr[idx_list[-1]:]))
        return sum(sum_list)

t = int(input())
for t_itr in range(t):
    n = int(input())
    arr = list(map(int, input().rstrip().split()))
    result = alt_subsequence(arr, n)

    print(result)


t=int(input())
for i in range(t):
    n=int(input())
    x=list(map(int,input().split()))
    a=1
    j=0
    s=[]
    z=[]
    while(j<n):
        count=0
        while(j<n and a*x[j]>0):
            z.append(x[j])
            j=j+1
            count+=1
            continue
        if(count>0):
            s.append(max(z))
        z=[]
        count=0
        while(j<n and a*x[j]<0):
            z.append(x[j])
            j=j+1
            count=count+1
            continue
        if(count>0):
            s.append(max(z))
    print(sum(s))


t=int(input())
for i in range(t):
    n=int(input())
    x=list(map(int,input().split()))
    max=x[0]
    sum=0
    maxsign=x[0]/abs(x[0])
    for j in range(n):
        if(maxsign==x[j]/abs(x[j])):
            if(max<x[j]):
                max=x[j]
        else:
            maxsign=x[j]/abs(x[j])
            sum+=max
            max=x[j]
    sum+=max
    print(sum)


t=int(input())
for i in range(t):
    n=int(input())
    x=list(map(int,input().split()))
    a=1
    j=0
    s=[]
    z=[]
    while(j<n):
        count=0
        c=x[j]
        while(j<n and a*x[j]>0):
            if(x[j]>c):
                c=x[j]
            j=j+1
            count+=1
            continue
        if(count>0):
            s.append(c)
        count=0
        if(j<n):
            c=x[j]
        while(j<n and a*x[j]<0):
            if(x[j]>c):
                c=x[j]
            j=j+1
            count=count+1
            continue
        if(count>0):
            s.append(c)
    print(sum(s))


t=int(input())
for i in range(t):
    n=int(input())
    x=list(map(int,input().split()))
    j=0
    s=[]
    z=[]
    while(j<n):
        count=0
        while(j<n and x[j]>0):
            z.append(x[j])
            j=j+1
            count+=1
            continue
        if(count>0):
            s.append(max(z))
        z=[]
        count=0
        while(j<n and x[j]<0):
            z.append(x[j])
            j=j+1
            count=count+1
            continue
        if(count>0):
            s.append(max(z))
    print(sum(s))


def f(n,A):
    s = 0
    ent = A[0]
    for i in range(1,n):
        if A[i]*A[i-1]<0:
            s += ent
            ent = A[i]
        else:
            ent = max(ent,A[i])
    return s+ent

for i in range(int(input())):
    n = int(input())
    A = input().split(' ')
    for i in range(n):
        A[i] = int(A[i])
    print(f(n,A))


def f(n,A):
    s = 0
    ent = A[0]
    for i in range(1,n):
        if A[i]*A[i-1]<0:
            s += ent
            ent = A[i]
        else:
            ent = max(A[i-1],A[i])
    return s+ent

for i in range(int(input())):
    n = int(input())
    A = input().split(' ')
    for i in range(n):
        A[i] = int(A[i])
    print(f(n,A))


gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	puts a.chunk { _1 < 0 }.sum { _1[1].max }
end


# frozen_string_literal: true

class Result
  def print_result
    gets
    arr = gets.split(' ').map(&:to_i)

    positive_arrs = [[], []]
    positive_arrs.each_with_index do |positive_arr, j|
      positive = j.zero?
      min = 0
      first = true
      arr.each do |i|
        if first
          if positive && i < 0
            next
          elsif !positive && i > 0
            next
          end

          first = false
        end

        if positive && min < i
          min = i
          next
        end

        if positive && i < 0
          positive = false
          positive_arr.push(min)
          min = i
          next
        end

        if !positive && (min == 0 || min < i) && i < 0
          min = i
          next
        end

        next unless !positive && i > 0

        positive = true
        positive_arr.push(min)
        min = i
      end

      positive_arr.push(min) if min != 0
    end

    puts(if positive_arrs[0].size == positive_arrs[1].size
           positive_arrs.map(&:sum).max
         elsif positive_arrs[0].size > positive_arrs[1].size
           positive_arrs[0].sum
         else
           positive_arrs[1].sum
    end)
  end

  private

  attr_reader :n
end

gets.to_i.times do
  Result.new.print_result
end


number_of_testcases = gets.to_s.to_i

number_of_testcases.times do |i|

  n = gets.to_s.to_i
  a = gets.to_s.split.map{|e|e.to_i}.push 0

  ans = 0
  s = []
  a.each do |k|
    if s.size > 0 && s[-1] * k <= 0
      ans += s.max
      s = []
    end
    s << k
  end
  # ans += s.max
  puts ans
end


1.upto(gets.to_i) do
  gets
  a = gets.split(' ').map(&:to_i)

  blocks = []
  while !a.empty?
    sign = a.first / a.first.abs
    blocks << a.take_while { |x| x / x.abs == sign }

    a = a.drop(blocks.last.size)
  end

  puts blocks.inject(0) { |s, e| s + e.max }
end


def my_function(no_of_disks=5, current_state=82195, unlock_state=64723):
    solution = 0
    for i in range(no_of_disks):
        x = abs(int(current_state[i]) - int(unlock_state[i]))
        y = abs(10 + int(current_state[i]) - (int(unlock_state[i])))
        z = abs(int(current_state[i]) - (10 + int(unlock_state[i])))
        solution += min(x, y, z)
    print solution

no_of_disks = int(raw_input())
current_state = raw_input()
unlock_state = raw_input()
my_function(no_of_disks, current_state, unlock_state)


def minimumMoves(n1,n2):

	cont = 0
	for i in range(len(n1)):
		a = int(n1[i])
		b = int(n2[i])
		cont += min(abs(a-b),10 - abs(a-b))

	return cont

n = int(raw_input())

num1 = raw_input()
num2 = raw_input()

print minimumMoves(num1,num2)


def minimumMoves(n1,n2):

    cont = 0
    for i in range(len(n1)):
        a = int(n1[i])
        b = int(n2[i])
        cont += min(abs(a-b),10 - abs(a-b))

    return cont

n = int(raw_input())

num1 = raw_input()
num2 = raw_input()

print minimumMoves(num1,num2)


a=input()
x=map(int,raw_input())
y=map(int,raw_input())
ans=0
for i in range(0,a):
	ans+=min(abs(x[i]-y[i]),10-abs(x[i]-y[i]))
print ans


import math
n=int(raw_input())
a=raw_input()
b=raw_input()
result=0
for i in range(n):
	ma,mi=max(int(a[i]),int(b[i])),min(int(a[i]),int(b[i]))
	if abs(int(a[i])-int(b[i])) > 5:
		k=0
		while True:
			k+=1
			ma+=1
			if ma%10==mi:
				result+=k
				break
	else:
		result+=abs(int(a[i])-int(b[i]))
print result


n = input()
lock = list(raw_input())
original = list(raw_input())
turns = 0
for comb, o in zip(lock, original):
    comb = int(comb)
    o = int(o)
    turn = min(abs(comb - o), (9 - max(comb, o) + min(comb, o) + 1 ) )
    print turn
    turns += turn

print turns


n = input()
lock = list(raw_input())
original = list(raw_input())
turns = 0
for comb, o in zip(lock, original):
    comb = int(comb)
    o = int(o)
    turn = min(abs(comb - o), (9 - max(comb, o) + min(comb, o) + 1 ) )
    turns += turn

print turns


n = input()
ci = input()
di = input()
c = "%d" % (ci)
d = "%d" % (di)
sum1 = 0
big = -1
small = -1
for i in range(n):
    if c[i] > d[i]:
        big = c[i]
        small = d[i]
    else:
        big = d[i]
        small = c[i]
    big = int(big)
    small = int(small)
    p1 = big - small
    p2 = (9 - big) + 1 + small
    if p1 > p2:
        sum1 += p2
    else:
        sum1 += p1
print sum1


n = input()
c = raw_input()
d = raw_input()
sum1 = 0
big = -1
small = -1
for i in range(n):
    if c[i] > d[i]:
        big = c[i]
        small = d[i]
    else:
        big = d[i]
        small = c[i]
    big = int(big)
    small = int(small)
    p1 = big - small
    p2 = (9 - big) + 1 + small
    if p1 > p2:
        sum1 += p2
    else:
        sum1 += p1
print sum1


n = int(raw_input())
a = raw_input()
b = raw_input()
ans = 0
for i in xrange(n):
	z = max(int(a[i]), int(b[i]))
	ans += min(z - min(int(a[i]), int(b[i])), min(int(a[i]), int(b[i]))+9+1-z)
print ans


input()
f=raw_input
a,b=map(int,f()),map(int,f())
print sum(min(abs(a[i]-b[i]),10-abs(a[i]-b[i]))) for i in xrange(len(a)))


input()
f=raw_input
a,b=map(int,f()),map(int,f())
print sum(min(abs(a[i]-b[i]),10-abs(a[i]-b[i])) for i in xrange(len(a)))


input()
f=raw_input
a,b=map(int,f()),map(int,f())
print sum(min(abs(a[i]-b[i]),abs(a[i]+10-b[i]),abs(a[i]-b[i]-10)) for i in xrange(len(a)))


def Menor(A,B):
    MAA=max(A,B)
    MII=min(A,B)
    minimo=MAA-MII
    MII=MII+10
    minimo2=MII-MAA
    return min(minimo,minimo2)
N=int(input())
A1=list(map(int,raw_input()))
A2=list(map(int,raw_input()))
suma=0
for k in range(len(A1)):
    suma+=Menor(A1[k],A2[k])
print suma


n = input()
s1 = raw_input()
s2 = raw_input()
ans = 0
for i in range( len( s1 ) ):
    tmp = abs( int( s1[ i ] ) - int( s2[ i ] ) )
    ans += min( tmp, 10 - tmp )
print( ans )


n=int(raw_input())
o=raw_input()
c=raw_input()
e=0
for i in range(0,n):
  a=int(o[i])
  b=int(c[i])
  d=a-b
  if d<0:
    d=-d
  if d>5:
    d=10-d
  e=e+d
print e


#!/usr/bin/python

if __name__ == '__main__':
    input()
    a = raw_input()
    b = raw_input()
    ret = 0
    for i,j in zip(a,b):
        ret += min(abs(int(i)-int(j)), 9-int(i)+int(j)+1, 9-int(j)+int(i)+1)
    print ret


#!/usr/bin/python

if __name__ == '__main__':
    input()
    a = str(input())
    b = str(input())
    ret = 0
    for i,j in zip(a,b):
        ret += min(abs(int(i)-int(j)), 9-int(i)+int(j)+1, 9-int(j)+int(i)+1)
    print ret


n = int(raw_input())
a = raw_input()
b = raw_input()
cnt = 0
for i in xrange(n):
	cnt += min(abs(int(a[i]) - int(b[i])), 10 - abs(int(a[i]) - int(b[i])))
print cnt


n = int(raw_input())

start = map(int, raw_input())
end = map(int, raw_input())

moves = 0
for i in range(n):
    start_i = start[i]
    end_i = end[i]
    moves += min(abs(start_i - end_i), 10 + min(start_i, end_i) - max(start_i, end_i))

print moves


n = int(raw_input())
s = zip(raw_input(), raw_input())
d = 0
for a, b in s:
    c = abs(int(a) - int(b))
    d += min(c, 10-c)
print d


#include<stdio.h>
int main()
{
    long long int i,j,n,a,b,r1,r2,d,sum;
    scanf("%lld%lld%lld",&n,&a,&b);
    sum=0;
    for(i=a,j=b;i>0&&j>0;i=i/10,j=j/10)
    {
        r1=i%10;
        r2=j%10;
        if(r1>r2)
        {
            d=r1-r2;
            if(d<=5)
            {
                sum=sum+d;
            }
            else
            {
                sum=sum+(9-r1)+(r2)+1;
            }
        }
        else if(r1<r2)
        {
             d=r2-r1;
             if(d<=5)
             {
                 sum=sum+d;
             }
             else
             {
                 sum=sum+(9-r2)+r1+1;
             }
        }
    }
    printf("%lld",sum);

}


#include<stdio.h>
int main()
{
    unsigned long long int i,j,n,a,b,r1,r2,d,sum,k;
    scanf("%lld%lld%lld",&n,&a,&b);
    sum=k=0;
    for(i=a,j=b;k<n;i=i/10,j=j/10)
    {
        r1=i%10;
        r2=j%10;
        if(r1>r2)
        {
            d=r1-r2;
            if(d<=5)
            {
                sum=sum+d;
            }
            else
            {
                sum=sum+(9-r1)+(r2)+1;
            }
        }
        else if(r1<r2)
        {
             d=r2-r1;
             if(d<=5)
             {
                 sum=sum+d;
             }
             else
             {
                 sum=sum+(9-r2)+r1+1;
             }
        }
        k++;
    }
    printf("%lld",sum);

}


#include<stdio.h>
int main()
{
    int n,i,k,l=0;
scanf("%d",&n);
char a[1000];
scanf("%s",a);
char b[1000];
scanf("%s",b);
for(i=0;i<n;i++)
{k=abs(a[i]-b[i]);
if(k>5)
k=10-k;
l=l+k;}
printf("%d",l);
}


#include<stdio.h>
int main()
{
    long long int i,j,n,r1,r2,d,sum,k;

    scanf("%lld",&n);
    char a[n],b[n];
    scanf("%s%s",a,b);
    sum=k=0;
    for(i=a,j=b;k<n;i=i/10,j=j/10)
    {
        r1=i%10;
        r2=j%10;
        if(r1>r2)
        {
            d=r1-r2;
            if(d<=5)
            {
                sum=sum+d;
            }
            else
            {
                sum=sum+(9-r1)+(r2)+1;
            }
        }
        else if(r1<r2)
        {
             d=r2-r1;
             if(d<=5)
             {
                 sum=sum+d;
             }
             else
             {
                 sum=sum+(9-r2)+r1+1;
             }
        }
        k++;
    }
    printf("%lld",sum);

}


#include<stdio.h>
int main()
{
    long long int i,j,n,a,b,r1,r2,d,sum,k;
    scanf("%lld%lld%lld",&n,&a,&b);
    sum=k=0;
    for(i=a,j=b;k<n;i=i/10,j=j/10)
    {
        r1=i%10;
        r2=j%10;
        if(r1>r2)
        {
            d=r1-r2;
            if(d<=5)
            {
                sum=sum+d;
            }
            else
            {
                sum=sum+(9-r1)+(r2)+1;
            }
        }
        else if(r1<r2)
        {
             d=r2-r1;
             if(d<=5)
             {
                 sum=sum+d;
             }
             else
             {
                 sum=sum+(9-r2)+r1+1;
             }
        }
        k++;
    }
    printf("%lld",sum);

}


#include<stdio.h>
int main()
{
	int n,m;
	scanf("%d %d",&n,&m);
		printf("%d",(m+n)/3);
	return 0;
}


#include <stdio.h>

int main(){

int n,i,c,d = 0;
char a[1001],b[1001];
scanf("%d", &n);
scanf("%s", a);
scanf("%s", b);
for(i = 0;i < n; i++){
    c = abs(b[i] - a[i]);
    if(c <= 5) d = d + c;
    else if(c > 5) d = d + (10-c);
}
printf("%d", d);

return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
    char str1[1001],str2[1002];
    int i,j,k,sum=0,num,n,ans=0;
    scanf("%d",&n);
    scanf("%s",str1);
    scanf("%s",str2);
    for(i=0;i<n;i++){
        if(str1[i]>str2[i]){
            num=str1[i]-str2[i];
            sum=('9'-str1[i])+(str2[i]-'0')+1;
            if(num>=sum)ans=ans+sum;
            if(num<sum)ans=ans+num;
        }
         if(str1[i]<str2[i]){
            num=str2[i]-str1[i];
            sum=('9'-str2[i])+(str1[i]-'0')+1;
            if(num>=sum)ans=ans+sum;
            if(num<sum)ans=ans+num;
        }
    }
    printf("%d",ans);
return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
    char str1[1001],str2[1002];
    int i,j,k,sum=0,num,n,ans=0;
    scanf("%d",&n);
    scanf("%s",str1);
    scanf("%s",str2);
    for(i=0;i<n;i++){
        if(str1[i]>str2[i]){
            num=str1[i]-str2[i];
            sum=('9'-str1[i])+(str2[i]-'0')+1;
            if(num>sum)ans=ans+sum;
            if(num<sum)ans=ans+num;
        }
         if(str1[i]<str2[i]){
            num=str2[i]-str1[i];
            sum=('9'-str2[i])+(str1[i]-'0')+1;
            if(num>sum)ans=ans+sum;
            if(num<sum)ans=ans+num;
        }
    }
    printf("%d",ans);
return 0;
}


#include <stdio.h>

int i, n, min, max;
char st[1001], nd[1001], nr1, nr2;

int main()
{
    scanf("%d", &n);
    scanf("%s", &st);
    scanf("%s", &nd);

    int k=0;
    for(i=0; i<n; i++)
    {
        if(st[i]<nd[i]){nr1=st[i]; nr2=nd[i];}
        else {nr1=nd[i]; nr2=st[i];}
        min=nr2-nr1;
        max=(nr1+10)-nr2;
        if(min<max)k+=min;
        else k+=max;
   }

   printf("%d", k);

    return 0;
}


#include <stdio.h>

int i, n, min, max;
char st[1001], nd[1001], nr1, nr2;

int main()
{
    scanf("%d", &n);
    scanf("%s", &st);
    scanf("%s", &nd);

    int k=0;
    for(i=0; i<n; i++)
    {
        if(st[i]<nd[i]){nr1=st[i]; nr2=nd[i];}
        else {nr1=nd[i]; nr2=st[i];}
        min=nr2-nr1;
        max=(nr1+10)-nr2;
        printf("nr1=%c nr2=%c min=%d max=%d\n", nr1, nr2, min, max);
        if(min<max)k+=min;
        else k+=max;
        printf("k=%d\n", k);
   }

   printf("%d", k);

    return 0;
}


#include <stdio.h>

int i, n, nr1, nr2, min, max, st[1001], nd[1001];

int main()
{
    scanf("%d", &n);
    scanf("%d", &nr1);
    scanf("%d", &nr2);

    for(i=n-1; i>=0; i--)
    {
        st[i]=nr1%10;
        nd[i]=nr2%10;
        nr1=nr1/10;
        nr2=nr2/10;
    }

    int k=0;
    for(i=0; i<n; i++)
    {
        if(st[i]<nd[i]){nr1=st[i]; nr2=nd[i];}
        else {nr1=nd[i]; nr2=st[i];}
        min=nr2-nr1;
        max=(nr1+10)-nr2;
        if(min<max)k+=min;
        else k+=max;
   }

   printf("%d", k);

    return 0;
}


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

int main()
{
  int n,i,cnt=0;
  scanf("%d",&n);
  char p[n],q[n];

      scanf("%s",&p);

     scanf("%s",&q);

   for(i=0;i<n;i++)
   {
       if(p[i]>q[i])
       {
          if(p[i]-q[i]<=5)
          {
              cnt=cnt+(p[i]-q[i]);
          }
          else if(p[i]-q[i]>5)
          {
              if(p[i]-q[i]==6)
              {
                  cnt=cnt+4;
              }
             else if(p[i]-q[i]==7)
              {
                  cnt=cnt+3;
              }
             else if(p[i]-q[i]==8)
              {
                  cnt=cnt+2;
              }

          }
       }
       else if(p[i]<q[i])
       {
          if(q[i]-p[i]<=5)
          {
              cnt=cnt+(q[i]-p[i]);
          }
          else if(q[i]-p[i]>5)
          {
              if(q[i]-p[i]==6)
              {
                  cnt=cnt+4;
              }
              else if(q[i]-p[i]==7)
              {
                  cnt=cnt+3;
              }
              else if(q[i]-p[i]==8)
              {
                  cnt=cnt+2;
              }
       }
       else{
        cnt=cnt+0;
       }
   }
   }
   printf("%d",cnt);

    return 0;
}


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

int main()
{
  int n,i,cnt=0;
  scanf("%d",&n);
  char p[n],q[n];

      scanf("%s",&p);

     scanf("%s",&q);

   for(i=0;i<n;i++)
   {
       if(p[i]>q[i])
       {
          if(p[i]-q[i]<=5)
          {
              cnt=cnt+(p[i]-q[i]);
          }
          else if(p[i]-q[i]>5)
          {
              cnt=cnt+q[i]+10-p[i];
          }
       }
       else if(p[i]<q[i])
       {
          if(q[i]-p[i]<=5)
          {
              cnt=cnt+(q[i]-p[i]);
          }
          else if(q[i]-p[i]>5)
          {
              cnt=cnt+p[i]+10-q[i];
       }
       else if (p[i]==q[i]){
        cnt=cnt+0;
       }
   }
   }
   printf("%d",cnt);

    return 0;
}


#include <stdio.h>
int main()
{
    int n,i,k=0;
    char a[10],b[10];
    scanf("%d%s%s",&n,a,b);
    for(i=0;i<n;i++)
    {
        if(b[i]==a[i]);
        else
            if(b[i]<a[i])
                if(a[i]-b[i]<5)
                    k=k+a[i]-b[i];
                else
                    k=k+b[i]+10-a[i];
        else
            if(b[i]-a[i]<5)
            k=k+b[i]-a[i];
            else
                k=k+a[i]+10-b[i];
        printf("%d ",k);
    }

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


#include <stdio.h>
int main()
{
    int n,i,k=0;
    char a[10],b[10];
    scanf("%d%s%s",&n,a,b);
    for(i=0;i<n;i++)
    {
        if(b[i]==a[i]);
        else
            if(b[i]<a[i])
                if(a[i]-b[i]<5)
                    k=k+a[i]-b[i];
                else
                    k=k+b[i]+10-a[i];
        else
            if(b[i]-a[i]<5)
            k=k+b[i]-a[i];
            else
                k=k+a[i]+10-b[i];
    }

    printf("%d",k);
    return 0;
}


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

int ctoi(char ch)
{
  return ch - '0';
}

int main()
{
  int n;
  int init, fin;
  int answer = 0;
  scanf("%d\n", &n);
  char *initial = malloc(sizeof(char) * (n + 1));
  char *final = malloc(sizeof(char) * (n + 1));
  scanf("%1000s\n", initial);
  scanf("%1000s", final);
  for(int i = 0; i < n; i++)
  {
    init = ctoi(initial[i]);
    fin = ctoi(final[i]);
    answer += abs(init - fin) > 5 ? 10 - abs(init - fin) : abs(init - fin);
  }
  printf("%d\n", answer);
  return 0;
}


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

int ctoi(char ch)
{
  return ch - '0';
}

int main()
{
  int n;
  int init, fin;
  int answer = 0;
  scanf("%d\n", &n);
  char *initial = malloc(sizeof(char) * (n + 1));
  char *final = malloc(sizeof(char) * (n + 1));
  scanf("%1000s\n", initial);
  scanf("%1000s", final);
  for(int i = 0; i < n; i++)
  {
    init = ctoi(initial[i]);
    fin = ctoi(final[i]);
    answer += abs(init - fin) > 5 ? 10 - abs(init - fin) : abs(init - fin);
  }
  free(initial);
  free(final);
  printf("%d\n", answer);
  return 0;
}


#include <stdio.h>

int min(int a, int b)
{
  return a < b ? a : b;
}

int compare(int initial, int final) //hello time limit excedeed, my old friend
{
  int first = 0;
  int second = 0;
  int initial_second = initial;
  while(initial != final)
  {
    if(initial + 1 > 9)
      initial = 0;
    else
      initial++;
    first++;
  }
  while(initial_second != final)
  {
    if(initial_second - 1 < 0)
      initial_second = 9;
    else
      initial_second--;
    second++;
  }
  return min(second, first);
}

int main()
{
  int n;
  int initial;
  int final;
  unsigned int answer = 0;
  scanf("%d\n", &n);
  scanf("%d\n", &initial);
  scanf("%d", &final);
  while(initial > 0)
  {
    answer += compare(initial % 10, final % 10);
    initial /= 10;
    final /= 10;
  }
  printf("%d\n", answer);
  return 0;
}