import java.util.Scanner;

public class Collecting_coins
{
    static long max(long a, long b, long c)
    {

        if (a>b && a>c) return a;
        else if (b>a && b>c) return b;
        else return c;
    }

    static long  equal(long a,long b,long c,long n)
    {
        long max_no = max(a,b,c);

        long k;
        if (a<max_no)
        {
            k = max_no - a;

            if(n-k >=0)
            {
                a = a + k;
                n = n - k;
            }
        }
        if (b<max_no)
        {
            k = max_no - b;

            if(n-k >= 0)
            {
                b = b + k;
                n = n - k;
            }
        }
        if (c<max_no)
        {
            k = max_no - c;

            if(n-k >=0)
            {
                c = c + k;
                n = n - k;
            }
        }

        if (a == b && b == c)
        {
            if(n%3==0) return 1;
            else return -1;
        }
        else return -1;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while (t-->0)
        {
            long a = in.nextInt();
            long b = in.nextInt();
            long c = in.nextInt();
            long n = in.nextInt();

            long res = equal(a,b,c,n);

            if (res==1) System.out.println("YES");
            else System.out.println("NO");

        }
    }
}


import java.util.Scanner;

public class Collecting_coins
{
    static long max(long a, long b, long c)
    {

        if (a>b && a>c) return a;
        else if (b>a && b>c) return b;
        else return c;
    }

    static long  equal(long a,long b,long c,long n)
    {
        long max_no = max(a,b,c);

        long k;
        if (a<max_no)
        {
            k = max_no - a;

            if(n-k >=0)
            {
                a = a + k;
                n = n - k;
            }
        }
        if (b<max_no)
        {
            k = max_no - b;

            if(n-k >= 0)
            {
                b = b + k;
                n = n - k;
            }
        }
        if (c<max_no)
        {
            k = max_no - c;

            if(n-k >=0)
            {
                c = c + k;
                n = n - k;
            }
        }

        if (a == b && b == c)
        {
            if(n%3==0) return 1;
            else return -1;
        }
        else return -1;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while (t-->0)
        {
            long a = in.nextLong();
            long b = in.nextLong();
            long c = in.nextLong();
            long n = in.nextLong();

            long res = equal(a,b,c,n);

            if (res==1) System.out.println("YES");
            else System.out.println("NO");

        }
    }
}


import java.util.Scanner;

public class collecting_coins {

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

	int t = sc.nextInt();
	for(int i=0; i<t; i++) {
		sum=0;
		int A[]= new int [4];

		for(int j=0; j<4;j++) {
			int a=sc.nextInt();
			A[j]= a;
			sum+=a;
		}

		if(sum%3==0) {
			int q = sum/3;
			A[3] -= q-A[0];
			A[3]-= q-A[1];
			A[3]-= q-A[2];
			if(A[3]==0) {
				System.out.println("YES");
			}
			else {
				System.out.println("NO");
			}

		}
		else {
			System.out.println("NO");
		}

	}

	}

}


package codeforce;

import java.util.Scanner;

public class collecting_coins {
	public static void coin(int[]A, int req ,int sum) {
		if(sum%3 !=0) {
			System.out.println("NO" );
		}
		else {
			for(int i=0;i<3; i++) {
				if(A[i]<=req) {
					A[3]= A[3]-(req-A[i]);
				}
				else {
					System.out.println("NO");
					return;
				}

			}
			if(A[3] == 0) {
				System.out.println("YES");
			}
			else {
				System.out.println("NO");
			}
		}

	}

	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int sum=0;
	int req = 0;

	int t = sc.nextInt();
	for(int i=0; i<t; i++) {
		sum=0;
		int A[]= new int [4];

		for(int j=0; j<4;j++) {
			int a=sc.nextInt();
			A[j]= a;
			sum+=a;
		}
		req = sum/3;
		coin(A,req,sum);

	}
}
}

//
//5
//5 3 2 8
//100 101 102 105
//3 2 1 100000000
//10 20 15 14
//101 101 101 3


package codeforce;

import java.util.Scanner;

public class collecting_coins {

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

	int t = sc.nextInt();
	for(int i=0; i<t; i++) {
		sum=0;
		int A[]= new int [4];

		for(int j=0; j<4;j++) {
			int a=sc.nextInt();
			A[j]= a;
			sum+=a;
		}

		if(sum%3==0) {
			int q = sum/3;
			A[3] -= q-A[0];
			A[3]-= q-A[1];
			A[3]-= q-A[2];
			if(A[3]==0) {
				System.out.println("YES");
			}
			else {
				System.out.println("NO");
			}

		}
		else {
			System.out.println("NO");
		}

	}

	}

}


import java.util.Scanner;

public class collecting_coins {

	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int sum=0;
	int t = sc.nextInt();
	for(int i=0; i<t; i++) {
		sum=0;

		for(int j=0; j<4;j++) {
			int a=sc.nextInt();
			sum+=a;
		}
		if(sum%3==0) {
			System.out.println("YES");
		}
		else {
			System.out.println("NO");
		}

	}

	}

}


import java.util.Scanner;

public class collecting_coins {
	public static void coin(int[]A, int req ,int sum) {
		if(sum%3 !=0) {
			System.out.println("NO" );
		}
		else {
			for(int i=0;i<3; i++) {
				if(A[i]<=req) {
					A[3]= A[3]-(req-A[i]);
				}
				else {
					System.out.println("NO");
					return;
				}

			}
			if(A[3] == 0) {
				System.out.println("YES");
			}
			else {
				System.out.println("NO");
			}
		}

	}
	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int sum=0;
	int req = 0;

	int t = sc.nextInt();
	for(int i=0; i<t; i++) {
		sum=0;
		int A[]= new int [4];

		for(int j=0; j<4;j++) {
			int a=sc.nextInt();
			A[j]= a;
			sum+=a;
		}
		req = sum/3;
		coin(A,req,sum);

	}
}
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
        }
        int n=sc.nextInt();
        Arrays.sort(arr);
        int temp1=arr[2]-arr[0];
        temp1=temp1+arr[2]-arr[1];
        n=n-temp1;
        if(n%3==0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
        }
        int n=sc.nextInt();
        Arrays.sort(arr);
        int temp1=arr[2]-arr[0];
        temp1=temp1+arr[2]-arr[1];
        n=n-temp1;
        if(n%3==0&&n!=0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        int sum=0;
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
            sum=sum+arr[i];
        }
        int n=sc.nextInt();
        sum=sum+n;

        if(sum%3==0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
        }
        int n=sc.nextInt();
        Arrays.sort(arr);
        int temp1=arr[2]-arr[0];

        temp1=temp1+arr[2]-arr[1];
        n=n-temp1;
        //System.out.println(n);
        if(n%3==0&&n>=0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
            arr[i]=arr[i]+1;
        }
        int n=sc.nextInt();
        Arrays.sort(arr);
        int temp1=arr[2]-arr[0];

        temp1=temp1+arr[2]-arr[1];
        n=n-3-temp1;
        if(n%3==0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
        }
        int n=sc.nextInt();
        Arrays.sort(arr);
        int temp1=arr[2]-arr[0];

        temp1=temp1+arr[2]-arr[1];
        n=n-temp1;
        if(n%3==0&&n>0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {
  public static void main(String args[]) throws IOException {

    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int arr[] =new int[3];
        for(int i=0;i<3;i++){
            arr[i]=sc.nextInt();
        }
        int n=sc.nextInt();
        Arrays.sort(arr);
        int temp1=arr[2]-arr[0];

        temp1=temp1+arr[2]-arr[1];
        n=n-temp1;
        if(n%3==0){System.out.println("YES");}
        else{System.out.println("NO");}

    }
  }
}


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

public class Main {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream);

        /*String [] words = {"sanan","natalia","mariya","veronika","barbora","maryna"};
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        out.println(trie.search("sanan"));
        out.println(trie.startsWith("san"));
        out.println(trie.search("mar"));
        out.println(trie.startsWith("mar"));*/
        int t = in.nextInt();
        while (t -- > 0) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            int n = in.nextInt();
            int value = a + b + c + n;
            if(value%3==0) {
                out.println("YES");
            }
            else {
                out.println("NO");
            }
        }

        out.flush();
    }

    private static void randomlyFillAnArray(int [] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*Integer.MAX_VALUE);
        }
    }

    private static void permutationOfNumbers(int n, int m, int [] a, int index) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=m; i++) {
            a[index] = i;
            permutationOfNumbers(n,m,a,index + 1);
        }
    }

    private static void permutationOfLetters( char m, int index, char[] a) {
        if(index == a.length) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (char c = 'a'; c <=m; c++) {
            a[index] = c;
            permutationOfLetters(m,index + 1, a);
        }
    }

    private static void permutations(int n, int index, int [] a, boolean [] used) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=n; i++) {
            if(used[i]) continue;
            a[index] = i;
            used[i] = true;
            permutations(n,index + 1,a,used);
            used[i] = false;
        }
    }

    private static boolean correct(String s) {
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()) {
            if(c == '(' || c == '[') {
                stack.push(c);
            }
            else {
                if(stack.isEmpty()) return false;
                char peek = stack.peek();
                if(peek == '(' && c == ']') return false;
                if(peek == '[' && c == ')') return false;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    private static void divideNumber(int sum, int last, int n, List<Integer> current) {
        if(sum > n) {
            return;
        }
        if(sum == n) {
            System.out.println(current);
            return;
        }
        for (int i = last; i <= n - sum ; i++) {
            current.add(i);
            divideNumber( sum + i, i,n,current);
            current.remove(current.size() - 1);
        }
    }
    private static void fishki(String s, int n, int m) {
        if(s.length() == n) {
            if(m == 0) {
                System.out.println(s);
            }
            return;
        }

        fishki(s + "*", n, m - 1);
        fishki(s + ".", n, m);
    }
    private static boolean check(String s) {
        for (int i = 0; i < s.length(); i++) {
            if(i > 0 && s.charAt(i) == '*' && s.charAt(i-1) == '*') return false;
        }
        return true;
    }
    private static boolean [] erath() {
        boolean[] isPrime = new boolean[200_000 + 1];
        Arrays.fill(isPrime,true);
        isPrime[0] = false;
        isPrime[1] = false;
        int n = isPrime.length - 1;
        for (int i = 2; i*i<=n; i++) {
            if(isPrime[i]) {
                for (int j = i*i; j <=n; j+=i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    public static long gcd(long a, long b) {
       while (b > 0) {
           long temp = a;
           a = b;
           b = temp%b;
       }
       return a;
    }

    private static int factorization(long n) {
        Set<Long> set = new HashSet<>();
        for(long i = 2; i * i <=n; i++) {
            while (n % i == 0) {
                set.add(i);
                n /= i;
            }
        }
        if(n > 1) set.add(n);
        return set.size();
    }
}

class LetterWithFrequency {
    private char letter;
    private int frequency;

    public char getLetter() {
        return letter;
    }

    public void setLetter(char letter) {
        this.letter = letter;
    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }

    public LetterWithFrequency(char letter, int frequency) {
        this.letter = letter;
        this.frequency = frequency;
    }
}

class InputReader extends BufferedReader {
    StringTokenizer tokenizer;

    public InputReader(InputStream inputStream) {
        super(new InputStreamReader(inputStream), 32768);
    }

    public InputReader(String filename) {
        super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(readLine());
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        return tokenizer.nextToken();
    }

    public Integer nextInt(){
        return Integer.valueOf(next());
    }
    public Long nextLong() {
        return  Long.valueOf(next());
    }
    public Double nextDouble() {
        return Double.valueOf(next());
    }
    static class OutputWriter extends PrintWriter {
        public OutputWriter(OutputStream outputStream) {
            super(outputStream);
        }

        public OutputWriter(Writer writer) {
            super(writer);
        }

        public OutputWriter(String filename) throws FileNotFoundException {
            super(filename);
        }

        public void close() {
            super.close();
        }
    }
}


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

public class Main {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream);

        /*String [] words = {"sanan","natalia","mariya","veronika","barbora","maryna"};
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        out.println(trie.search("sanan"));
        out.println(trie.startsWith("san"));
        out.println(trie.search("mar"));
        out.println(trie.startsWith("mar"));*/
        int t = in.nextInt();
        while (t -- > 0) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            int n = in.nextInt();
            boolean found = false;
            for (int i = 0; i <= n; i++) {
                int newA = a + i;
                int diifB = newA - b;
                int diffC = newA - c;
                if (diifB + diffC + i == n) {
                    found = true;
                    break;
                }
            }
            if(found) {
                out.println("YES");
            }
            else {
                out.println("NO");
            }
        }

        out.flush();
    }

    private static void randomlyFillAnArray(int [] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*Integer.MAX_VALUE);
        }
    }

    private static void permutationOfNumbers(int n, int m, int [] a, int index) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=m; i++) {
            a[index] = i;
            permutationOfNumbers(n,m,a,index + 1);
        }
    }

    private static void permutationOfLetters( char m, int index, char[] a) {
        if(index == a.length) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (char c = 'a'; c <=m; c++) {
            a[index] = c;
            permutationOfLetters(m,index + 1, a);
        }
    }

    private static void permutations(int n, int index, int [] a, boolean [] used) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=n; i++) {
            if(used[i]) continue;
            a[index] = i;
            used[i] = true;
            permutations(n,index + 1,a,used);
            used[i] = false;
        }
    }

    private static boolean correct(String s) {
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()) {
            if(c == '(' || c == '[') {
                stack.push(c);
            }
            else {
                if(stack.isEmpty()) return false;
                char peek = stack.peek();
                if(peek == '(' && c == ']') return false;
                if(peek == '[' && c == ')') return false;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    private static void divideNumber(int sum, int last, int n, List<Integer> current) {
        if(sum > n) {
            return;
        }
        if(sum == n) {
            System.out.println(current);
            return;
        }
        for (int i = last; i <= n - sum ; i++) {
            current.add(i);
            divideNumber( sum + i, i,n,current);
            current.remove(current.size() - 1);
        }
    }
    private static void fishki(String s, int n, int m) {
        if(s.length() == n) {
            if(m == 0) {
                System.out.println(s);
            }
            return;
        }

        fishki(s + "*", n, m - 1);
        fishki(s + ".", n, m);
    }
    private static boolean check(String s) {
        for (int i = 0; i < s.length(); i++) {
            if(i > 0 && s.charAt(i) == '*' && s.charAt(i-1) == '*') return false;
        }
        return true;
    }
    private static boolean [] erath() {
        boolean[] isPrime = new boolean[200_000 + 1];
        Arrays.fill(isPrime,true);
        isPrime[0] = false;
        isPrime[1] = false;
        int n = isPrime.length - 1;
        for (int i = 2; i*i<=n; i++) {
            if(isPrime[i]) {
                for (int j = i*i; j <=n; j+=i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    public static long gcd(long a, long b) {
       while (b > 0) {
           long temp = a;
           a = b;
           b = temp%b;
       }
       return a;
    }

    private static int factorization(long n) {
        Set<Long> set = new HashSet<>();
        for(long i = 2; i * i <=n; i++) {
            while (n % i == 0) {
                set.add(i);
                n /= i;
            }
        }
        if(n > 1) set.add(n);
        return set.size();
    }
}

class LetterWithFrequency {
    private char letter;
    private int frequency;

    public char getLetter() {
        return letter;
    }

    public void setLetter(char letter) {
        this.letter = letter;
    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }

    public LetterWithFrequency(char letter, int frequency) {
        this.letter = letter;
        this.frequency = frequency;
    }
}

class InputReader extends BufferedReader {
    StringTokenizer tokenizer;

    public InputReader(InputStream inputStream) {
        super(new InputStreamReader(inputStream), 32768);
    }

    public InputReader(String filename) {
        super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(readLine());
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        return tokenizer.nextToken();
    }

    public Integer nextInt(){
        return Integer.valueOf(next());
    }
    public Long nextLong() {
        return  Long.valueOf(next());
    }
    public Double nextDouble() {
        return Double.valueOf(next());
    }
    static class OutputWriter extends PrintWriter {
        public OutputWriter(OutputStream outputStream) {
            super(outputStream);
        }

        public OutputWriter(Writer writer) {
            super(writer);
        }

        public OutputWriter(String filename) throws FileNotFoundException {
            super(filename);
        }

        public void close() {
            super.close();
        }
    }
}


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

public class Main {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream);

        /*String [] words = {"sanan","natalia","mariya","veronika","barbora","maryna"};
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        out.println(trie.search("sanan"));
        out.println(trie.startsWith("san"));
        out.println(trie.search("mar"));
        out.println(trie.startsWith("mar"));*/
        int t = in.nextInt();
        while (t -- > 0) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            int n = in.nextInt();
            boolean found = false;
            for (int i = 0; i <= n; i++) {
                int newA = a + i;
                int diifB = newA - b;
                int diffC = newA - c;
                if (diifB > 0 && diffC > 0 && diifB + diffC + i == n) {
                    found = true;
                    break;
                }
            }
            if(found) {
                out.println("YES");
            }
            else {
                out.println("NO");
            }
        }

        out.flush();
    }

    private static void randomlyFillAnArray(int [] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*Integer.MAX_VALUE);
        }
    }

    private static void permutationOfNumbers(int n, int m, int [] a, int index) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=m; i++) {
            a[index] = i;
            permutationOfNumbers(n,m,a,index + 1);
        }
    }

    private static void permutationOfLetters( char m, int index, char[] a) {
        if(index == a.length) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (char c = 'a'; c <=m; c++) {
            a[index] = c;
            permutationOfLetters(m,index + 1, a);
        }
    }

    private static void permutations(int n, int index, int [] a, boolean [] used) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=n; i++) {
            if(used[i]) continue;
            a[index] = i;
            used[i] = true;
            permutations(n,index + 1,a,used);
            used[i] = false;
        }
    }

    private static boolean correct(String s) {
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()) {
            if(c == '(' || c == '[') {
                stack.push(c);
            }
            else {
                if(stack.isEmpty()) return false;
                char peek = stack.peek();
                if(peek == '(' && c == ']') return false;
                if(peek == '[' && c == ')') return false;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    private static void divideNumber(int sum, int last, int n, List<Integer> current) {
        if(sum > n) {
            return;
        }
        if(sum == n) {
            System.out.println(current);
            return;
        }
        for (int i = last; i <= n - sum ; i++) {
            current.add(i);
            divideNumber( sum + i, i,n,current);
            current.remove(current.size() - 1);
        }
    }
    private static void fishki(String s, int n, int m) {
        if(s.length() == n) {
            if(m == 0) {
                System.out.println(s);
            }
            return;
        }

        fishki(s + "*", n, m - 1);
        fishki(s + ".", n, m);
    }
    private static boolean check(String s) {
        for (int i = 0; i < s.length(); i++) {
            if(i > 0 && s.charAt(i) == '*' && s.charAt(i-1) == '*') return false;
        }
        return true;
    }
    private static boolean [] erath() {
        boolean[] isPrime = new boolean[200_000 + 1];
        Arrays.fill(isPrime,true);
        isPrime[0] = false;
        isPrime[1] = false;
        int n = isPrime.length - 1;
        for (int i = 2; i*i<=n; i++) {
            if(isPrime[i]) {
                for (int j = i*i; j <=n; j+=i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    public static long gcd(long a, long b) {
       while (b > 0) {
           long temp = a;
           a = b;
           b = temp%b;
       }
       return a;
    }

    private static int factorization(long n) {
        Set<Long> set = new HashSet<>();
        for(long i = 2; i * i <=n; i++) {
            while (n % i == 0) {
                set.add(i);
                n /= i;
            }
        }
        if(n > 1) set.add(n);
        return set.size();
    }
}

class LetterWithFrequency {
    private char letter;
    private int frequency;

    public char getLetter() {
        return letter;
    }

    public void setLetter(char letter) {
        this.letter = letter;
    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }

    public LetterWithFrequency(char letter, int frequency) {
        this.letter = letter;
        this.frequency = frequency;
    }
}

class InputReader extends BufferedReader {
    StringTokenizer tokenizer;

    public InputReader(InputStream inputStream) {
        super(new InputStreamReader(inputStream), 32768);
    }

    public InputReader(String filename) {
        super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(readLine());
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        return tokenizer.nextToken();
    }

    public Integer nextInt(){
        return Integer.valueOf(next());
    }
    public Long nextLong() {
        return  Long.valueOf(next());
    }
    public Double nextDouble() {
        return Double.valueOf(next());
    }
    static class OutputWriter extends PrintWriter {
        public OutputWriter(OutputStream outputStream) {
            super(outputStream);
        }

        public OutputWriter(Writer writer) {
            super(writer);
        }

        public OutputWriter(String filename) throws FileNotFoundException {
            super(filename);
        }

        public void close() {
            super.close();
        }
    }
}


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

public class Main {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream);

        /*String [] words = {"sanan","natalia","mariya","veronika","barbora","maryna"};
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        out.println(trie.search("sanan"));
        out.println(trie.startsWith("san"));
        out.println(trie.search("mar"));
        out.println(trie.startsWith("mar"));*/
        int t = in.nextInt();
        while (t -- > 0) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            int n = in.nextInt();
            int value = a + b + c + n;
            if(value%3==0) {
                int m = value/3;
                if(m - a >=0 && m-b>=0 && m-c>=0) {
                    out.println("YES");
                }
                else {
                    out.println("NO");
                }
            }
            else {
                out.println("NO");
            }
        }

        out.flush();
    }

    private static void randomlyFillAnArray(int [] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*Integer.MAX_VALUE);
        }
    }

    private static void permutationOfNumbers(int n, int m, int [] a, int index) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=m; i++) {
            a[index] = i;
            permutationOfNumbers(n,m,a,index + 1);
        }
    }

    private static void permutationOfLetters( char m, int index, char[] a) {
        if(index == a.length) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (char c = 'a'; c <=m; c++) {
            a[index] = c;
            permutationOfLetters(m,index + 1, a);
        }
    }

    private static void permutations(int n, int index, int [] a, boolean [] used) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=n; i++) {
            if(used[i]) continue;
            a[index] = i;
            used[i] = true;
            permutations(n,index + 1,a,used);
            used[i] = false;
        }
    }

    private static boolean correct(String s) {
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()) {
            if(c == '(' || c == '[') {
                stack.push(c);
            }
            else {
                if(stack.isEmpty()) return false;
                char peek = stack.peek();
                if(peek == '(' && c == ']') return false;
                if(peek == '[' && c == ')') return false;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    private static void divideNumber(int sum, int last, int n, List<Integer> current) {
        if(sum > n) {
            return;
        }
        if(sum == n) {
            System.out.println(current);
            return;
        }
        for (int i = last; i <= n - sum ; i++) {
            current.add(i);
            divideNumber( sum + i, i,n,current);
            current.remove(current.size() - 1);
        }
    }
    private static void fishki(String s, int n, int m) {
        if(s.length() == n) {
            if(m == 0) {
                System.out.println(s);
            }
            return;
        }

        fishki(s + "*", n, m - 1);
        fishki(s + ".", n, m);
    }
    private static boolean check(String s) {
        for (int i = 0; i < s.length(); i++) {
            if(i > 0 && s.charAt(i) == '*' && s.charAt(i-1) == '*') return false;
        }
        return true;
    }
    private static boolean [] erath() {
        boolean[] isPrime = new boolean[200_000 + 1];
        Arrays.fill(isPrime,true);
        isPrime[0] = false;
        isPrime[1] = false;
        int n = isPrime.length - 1;
        for (int i = 2; i*i<=n; i++) {
            if(isPrime[i]) {
                for (int j = i*i; j <=n; j+=i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    public static long gcd(long a, long b) {
       while (b > 0) {
           long temp = a;
           a = b;
           b = temp%b;
       }
       return a;
    }

    private static int factorization(long n) {
        Set<Long> set = new HashSet<>();
        for(long i = 2; i * i <=n; i++) {
            while (n % i == 0) {
                set.add(i);
                n /= i;
            }
        }
        if(n > 1) set.add(n);
        return set.size();
    }
}

class LetterWithFrequency {
    private char letter;
    private int frequency;

    public char getLetter() {
        return letter;
    }

    public void setLetter(char letter) {
        this.letter = letter;
    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }

    public LetterWithFrequency(char letter, int frequency) {
        this.letter = letter;
        this.frequency = frequency;
    }
}

class InputReader extends BufferedReader {
    StringTokenizer tokenizer;

    public InputReader(InputStream inputStream) {
        super(new InputStreamReader(inputStream), 32768);
    }

    public InputReader(String filename) {
        super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(readLine());
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        return tokenizer.nextToken();
    }

    public Integer nextInt(){
        return Integer.valueOf(next());
    }
    public Long nextLong() {
        return  Long.valueOf(next());
    }
    public Double nextDouble() {
        return Double.valueOf(next());
    }
    static class OutputWriter extends PrintWriter {
        public OutputWriter(OutputStream outputStream) {
            super(outputStream);
        }

        public OutputWriter(Writer writer) {
            super(writer);
        }

        public OutputWriter(String filename) throws FileNotFoundException {
            super(filename);
        }

        public void close() {
            super.close();
        }
    }
}


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

public class Main {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream);

        /*String [] words = {"sanan","natalia","mariya","veronika","barbora","maryna"};
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        out.println(trie.search("sanan"));
        out.println(trie.startsWith("san"));
        out.println(trie.search("mar"));
        out.println(trie.startsWith("mar"));*/
        int t = in.nextInt();
        while (t -- > 0) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            int n = in.nextInt();
            boolean found = false;
            for (int i = 0; i <= n; i++) {
                int newA = a + i;
                int diifB = newA - b;
                int diffC = newA - c;
                if (diifB >= 0 && diffC >= 0 && diifB + diffC + i == n) {
                    found = true;
                    break;
                }
            }
            if(found) {
                out.println("YES");
            }
            else {
                out.println("NO");
            }
        }

        out.flush();
    }

    private static void randomlyFillAnArray(int [] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*Integer.MAX_VALUE);
        }
    }

    private static void permutationOfNumbers(int n, int m, int [] a, int index) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=m; i++) {
            a[index] = i;
            permutationOfNumbers(n,m,a,index + 1);
        }
    }

    private static void permutationOfLetters( char m, int index, char[] a) {
        if(index == a.length) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (char c = 'a'; c <=m; c++) {
            a[index] = c;
            permutationOfLetters(m,index + 1, a);
        }
    }

    private static void permutations(int n, int index, int [] a, boolean [] used) {
        if(index == n) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for (int i = 1; i <=n; i++) {
            if(used[i]) continue;
            a[index] = i;
            used[i] = true;
            permutations(n,index + 1,a,used);
            used[i] = false;
        }
    }

    private static boolean correct(String s) {
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()) {
            if(c == '(' || c == '[') {
                stack.push(c);
            }
            else {
                if(stack.isEmpty()) return false;
                char peek = stack.peek();
                if(peek == '(' && c == ']') return false;
                if(peek == '[' && c == ')') return false;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    private static void divideNumber(int sum, int last, int n, List<Integer> current) {
        if(sum > n) {
            return;
        }
        if(sum == n) {
            System.out.println(current);
            return;
        }
        for (int i = last; i <= n - sum ; i++) {
            current.add(i);
            divideNumber( sum + i, i,n,current);
            current.remove(current.size() - 1);
        }
    }
    private static void fishki(String s, int n, int m) {
        if(s.length() == n) {
            if(m == 0) {
                System.out.println(s);
            }
            return;
        }

        fishki(s + "*", n, m - 1);
        fishki(s + ".", n, m);
    }
    private static boolean check(String s) {
        for (int i = 0; i < s.length(); i++) {
            if(i > 0 && s.charAt(i) == '*' && s.charAt(i-1) == '*') return false;
        }
        return true;
    }
    private static boolean [] erath() {
        boolean[] isPrime = new boolean[200_000 + 1];
        Arrays.fill(isPrime,true);
        isPrime[0] = false;
        isPrime[1] = false;
        int n = isPrime.length - 1;
        for (int i = 2; i*i<=n; i++) {
            if(isPrime[i]) {
                for (int j = i*i; j <=n; j+=i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    public static long gcd(long a, long b) {
       while (b > 0) {
           long temp = a;
           a = b;
           b = temp%b;
       }
       return a;
    }

    private static int factorization(long n) {
        Set<Long> set = new HashSet<>();
        for(long i = 2; i * i <=n; i++) {
            while (n % i == 0) {
                set.add(i);
                n /= i;
            }
        }
        if(n > 1) set.add(n);
        return set.size();
    }
}

class LetterWithFrequency {
    private char letter;
    private int frequency;

    public char getLetter() {
        return letter;
    }

    public void setLetter(char letter) {
        this.letter = letter;
    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }

    public LetterWithFrequency(char letter, int frequency) {
        this.letter = letter;
        this.frequency = frequency;
    }
}

class InputReader extends BufferedReader {
    StringTokenizer tokenizer;

    public InputReader(InputStream inputStream) {
        super(new InputStreamReader(inputStream), 32768);
    }

    public InputReader(String filename) {
        super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(readLine());
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        return tokenizer.nextToken();
    }

    public Integer nextInt(){
        return Integer.valueOf(next());
    }
    public Long nextLong() {
        return  Long.valueOf(next());
    }
    public Double nextDouble() {
        return Double.valueOf(next());
    }
    static class OutputWriter extends PrintWriter {
        public OutputWriter(OutputStream outputStream) {
            super(outputStream);
        }

        public OutputWriter(Writer writer) {
            super(writer);
        }

        public OutputWriter(String filename) throws FileNotFoundException {
            super(filename);
        }

        public void close() {
            super.close();
        }
    }
}


import java.util.*;
/**
 *
 * @author Pruthvi
 */
public class JavaApplication73 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int t=sc.nextInt();
        int a,b,c,n,k;
        boolean flag=false;
        for(int i=0;i<t;i++)
        {
          a=sc.nextInt();
          b=sc.nextInt();
          c=sc.nextInt();
          n=sc.nextInt();
          if((a+b+c+n)%3==0 )
          {
             k =(a+b+c+n)/3;
             if(k-a>=0 && k-b>=0 && k-c>=0)
             {
           System.out.println("YES");
             }
             else
                System.out.println("NO");
          }
          else
         System.out.println("NO");
        }

    }

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication73;
import java.util.*;
/**
 *
 * @author Pruthvi
 */
public class JavaApplication73 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int t=sc.nextInt();
        int a,b,c,n,k;
        boolean flag=false;
        for(int i=0;i<t;i++)
        {
          a=sc.nextInt();
          b=sc.nextInt();
          c=sc.nextInt();
          n=sc.nextInt();
          if((a+b+c+n)%3==0 )
          {
             k= (a+b+c+n)/3;
             if(k-a>0 && k-b>0 && k-c>0)
             {
           System.out.println("YES");
             }
             else
                System.out.println("NO");
          }
          else
         System.out.println("NO");
        }

    }

}


import java.util.*;
/**
 *
 * @author Pruthvi
 */
public class JavaApplication73 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int t=sc.nextInt();
        int a,b,c,n,k;
        boolean flag=false;
        for(int i=0;i<t;i++)
        {
          a=sc.nextInt();
          b=sc.nextInt();
          c=sc.nextInt();
          n=sc.nextInt();
          if((a+b+c+n)%3==0 )
          {
             k =(a+b+c+n)/3;
             if(k-a>0 && k-b>0 && k-c>0)
             {
           System.out.println("YES");
             }
             else
                System.out.println("NO");
          }
          else
         System.out.println("NO");
        }

    }

}


import java.util.*;

public class JavaApplication73 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int t=sc.nextInt();
        int a,b,c,n;
        boolean flag=false;
        for(int i=0;i<t;i++)
        {
          a=sc.nextInt();
          b=sc.nextInt();
          c=sc.nextInt();
          n=sc.nextInt();
          if((a+b+c+n)%3==0)
          {
           System.out.println("YES");

          }
          else
         System.out.println("NO");
        }

    }

}


import java.util.*;
/**
 *
 * @author Pruthvi
 */
public class JavaApplication73 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int t=sc.nextInt();
        int a,b,c,n;
        boolean flag=false;
        for(int i=0;i<t;i++)
        {
          a=sc.nextInt();
          b=sc.nextInt();
          c=sc.nextInt();
          n=sc.nextInt();
          if((a+b+c+n)%3==0 && a<(a+b+c+n)/3 && b<(a+b+c+n)/3 && c<(a+b+c+n)/3)
          {
           System.out.println("YES");

          }
          else
         System.out.println("NO");
        }

    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class hjf
{
    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(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 nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String[] args)
    {
        FastReader fastReader = new FastReader();
        StringBuilder output = new StringBuilder();

        int t = fastReader.nextInt();

        for(int i=1;i<=t;i++)
        {
            int a = fastReader.nextInt();
            int b = fastReader.nextInt();
            int c = fastReader.nextInt();
            int n = fastReader.nextInt();

            int sum = (a+b+c+n);

            if(sum%3!=0)
                output.append("NO\n");
            else
                output.append("YES\n");
        }

        System.out.println(output.toString());

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class hjf
{
    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(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 nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String[] args)
    {
        FastReader fastReader = new FastReader();
        StringBuilder output = new StringBuilder();

        int t = fastReader.nextInt();

        for(int i=1;i<=t;i++)
        {
            int a = fastReader.nextInt();
            int b = fastReader.nextInt();
            int c = fastReader.nextInt();
            int n = fastReader.nextInt();

            int sum = (a+b+c+n);
            int div = sum/3;

            if(sum%3!=0)
                output.append("NO\n");
            else
            {
//                if((div-a>=n)||(div-b>=n)||(div-c>=n))
//                    output.append("NO\n");
//                else
//                    output.append("YES\n");

                if((div-a)+(div-b)+(div-c)>n)
                    output.append("NO\n");
                else
                    output.append("YES\n");
            }
        }

        System.out.println(output.toString());

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class hjf
{
    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(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 nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String[] args)
    {
        FastReader fastReader = new FastReader();
        StringBuilder output = new StringBuilder();

        int t = fastReader.nextInt();

        for(int i=1;i<=t;i++)
        {
            int a = fastReader.nextInt();
            int b = fastReader.nextInt();
            int c = fastReader.nextInt();
            int n = fastReader.nextInt();

            int sum = (a+b+c+n);
            int div = sum/3;

            a = div-a;
            b = div -b;
            c = div-c;

            if(a+c+b==n&&a>0&&b>0&&c>0)
                output.append("YES\n");
            else
                output.append("NO\n");
        }

        System.out.println(output.toString());

    }
}


// Author: sighduck
// URL: https://codeforces.com/contest/1174/problem/B

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

func Solve(n int, a []int) []int {
	even := 0
	odd := 0
	for _, elem := range a {
		if elem%2 == 0 {
			even += 1
		} else {
			odd += 1
		}
	}
	if even == n || odd == n {
		return a
	}
	sort.Ints(a)
	return a
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &a[i])
	}

	solution := Solve(n, a)
	for _, elem := range solution {
		fmt.Fprintf(writer, "%d ", elem)
	}
	fmt.Fprintf(writer, "\n")
}


<?php
# 1174b
$stdin = STDIN;

$n = trim(fgets($stdin));
$a = explode(' ', trim(fgets($stdin)));
if ($n < 4) {
    sort($a, SORT_STRING);
} else {
    usort($a, static function (string $a, string $b){
        if (((int)$a + (int)$b) % 2 === 0 || $a === $b) {
            return 0;
        }
        $c = [$a, $b];
        sort($c);
        return $a === $c[0] ? -1 : +1;
    });
}
echo implode(' ', $a);


<?php
# 1174b
$stdin = STDIN;

$n = trim(fgets($stdin));
$a = explode(' ', trim(fgets($stdin)));
sort($a, SORT_STRING);

echo implode(' ', $a);


<?php
# 1174b
$stdin = STDIN;

$n = trim(fgets($stdin));
$a = explode(' ', trim(fgets($stdin)));
$mods = [0, 0];
$needSort = false;
foreach ($a as $item) {
    $mods[$item % 2]++;
    if ($mods[0] !== 0 && $mods[1] !== 0) {
        $needSort = true;
        break;
    }
}

if ($needSort) {
    sort($a);
}
echo implode(' ', $a);


<?php
# 1174b
$stdin = STDIN;

$n = trim(fgets($stdin));
$a = explode(' ', trim(fgets($stdin)));
if ($n < 4) {
    sort($a, SORT_STRING);
} else {
    usort($a, static function (string $a, string $b){
        if (((int)$a + (int)$b) % 2 === 0 || $a === $b) {
            return 0;
        }
        $c = [$a, $b];
        sort($c, SORT_STRING);
        return $a === $c[0] ? -1 : +1;
    });
}
echo implode(' ', $a);


<?php
# 1174b
$stdin = STDIN;

$n = trim(fgets($stdin));
$a = explode(' ', trim(fgets($stdin)));
$mods = [0, 0];
foreach ($a as $item) {
    $mods[$item % 2]++;
}

if ($mods[0] !== 0 && $mods[1] !== 0) {
    sort($a);
}
echo implode(' ', $a);


<?php
# 1174b
$stdin = STDIN;

$n = trim(fgets($stdin));
$a = explode(' ', trim(fgets($stdin)));
$mods = [0, 0];
foreach ($a as $item) {
    $mods[$item % 2]++;
}

if ($mods[0] !== 0 && $mods[1] !== 0) {
    sort($a, SORT_STRING);
}
echo implode(' ', $a);


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <09/Jun/2019 03:31:05 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT), Gwalior

from __future__ import division, print_function
import sys

if sys.version_info.major == 2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    from __builtin__ import xrange as range

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline().strip()

def main():
    n = int(input())
    arr = get_array()
    even, odd = [], []
    for i in range(n):
        if arr[i] % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    if len(even) == 0 or len(odd) == 0:
        print(*arr)
        return
    print(*sorted(arr))

if __name__ == "__main__":
    main()


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <09/Jun/2019 03:36:32 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT), Gwalior

from __future__ import division, print_function
from io import IOBase, BytesIO
import sys
import os

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    from __builtin__ import xrange as range

'''BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill():
            pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill()
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode('ascii'))
            self.read = lambda: self.buffer.read().decode('ascii')
            self.readline = lambda: self.buffer.readline().decode('ascii')

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)'''

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline().rstrip('\r\n')

def main():
    n = int(input())
    arr = get_array()
    even, odd = [], []
    for i in range(n):
        if arr[i] % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    if len(even) == 0 or len(odd) == 0:
        print(*arr)
        return
    print(*sorted(arr))

if __name__ == "__main__":
    main()


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <09/Jun/2019 03:29:35 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT), Gwalior

from __future__ import division, print_function
import sys

if sys.version_info.major == 2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline().strip()

def main():
    n = int(input())
    arr = get_array()
    even, odd = [], []
    for i in range(n):
        if arr[i] % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    if len(even) == 0 or len(odd) == 0:
        print(*arr)
        return
    print(*sorted(arr))

if __name__ == "__main__":
    main()


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <09/Jun/2019 03:35:54 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT), Gwalior

from __future__ import division, print_function
from io import IOBase, BytesIO
import sys
import os

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    from __builtin__ import xrange as range

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill():
            pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill()
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode('ascii'))
            self.read = lambda: self.buffer.read().decode('ascii')
            self.readline = lambda: self.buffer.readline().decode('ascii')

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline().rstrip('\r\n')

def main():
    n = int(input())
    arr = get_array()
    even, odd = [], []
    for i in range(n):
        if arr[i] % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    if len(even) == 0 or len(odd) == 0:
        print(*arr)
        return
    print(*sorted(arr))

if __name__ == "__main__":
    main()


n = input()
a = map(int, raw_input().split())
e = 0
for i in xrange(n):
    if a[i] % 2 == 0: e += 1

if e == 0 or e == n: print ' '.join(map(str, a))
else: print ' '.join(map(str, sorted(a)))


n = int(input())
a = list(map(int, raw_input().split()))

if all(a[i] % 2 == 0 for i in range(n)) or all(a[i] % 2 == 1 for i in range(n)):
    print(' '.join(map(str, a)))
else:
    a.sort()
    print(' '.join(map(str, a)))


# -*- coding: utf-8 -*-
import sys,fractions,bisect
from math import factorial
def fi():
    return int(sys.stdin.readline())

def fi2():
    return map(int, sys.stdin.readline().split())

def fi3():
    return sys.stdin.readline()

def fo(*args):
    for s in args:
        sys.stdout.write(str(s)+' ')
    sys.stdout.write('\n')
INF=10**9+7
sys.setrecursionlimit(INF)

#main
n=fi()
a=fi2()
a1=list(a)
a1.sort()
o=0
e=0
for i in range(n):
    if a[i]%2==0:
        e+=1
    else:
        o+=1
if e==n or o==n:
    for i in range(n):
        a[i]=str(a[i])
    fo(" ".join(a))
else:
    for i in range(n):
        a1[i]=str(a1[i])
    fo(" ".join(a1))


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1:
			odd.append((arr[i],i))
			n1+=1
		else:
			even.append((arr[i],i))
			n2+=1

	odd.sort()
	even.sort()
	i=j=0
	out=[None]*(s)
	p=0
	while  i<n1 and j<n2:
		if odd[i][0]<even[j]:
			out[p],out[p+1]=odd[i][0],even[j][0]
		else:
			out[p+1],out[p]=odd[i][0],even[j][0]
		i,j,p=i+1,j+1,p+1
	while i<n1:
		out[odd[i][1]]=odd[i][0]
		i=i+1
	while j<n2:
		out[even[j][1]]=even[j][0]
	for i in xrange(s):
		print out[i],

if __name__ == '__main__':
	main()


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1:
			odd.append((arr[i],i))
			n1+=1
		else:
			even.append((arr[i],i))
			n2+=1

	odd.sort()
	even.sort()
	i=j=0
	out=[None]*(s)
	p=0
	while  i<n1 and j<n2:
		if odd[i][0]<even[j]:
			out[p],out[p+1]=odd[i][0],even[j][0]
		else:
			out[p+1],out[p]=odd[i][0],even[j][0]
		i,j,p=i+1,j+1,p+1
	while i<n1:
		out[odd[i][1]]=odd[i][0]
		i=i+1
	while j<n2:
		out[even[j][1]]=even[j][0]
		j+=1
	for i in xrange(s):
		print out[i],

if __name__ == '__main__':
	main()


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1==1:
			n1+=1
		else:
			n2+=1
	if n1>0 or n2>0:
		arr.sort()
	print " ".join(map(str,arr))

if __name__ == '__main__':
	main()


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1==1:
			odd.append((arr[i],i))
			n1+=1
		else:
			even.append((arr[i],i))
			n2+=1

	odd.sort()
	even.sort()
	i=j=0
	out=[None]*(s)
	p=0
	while  i<n1 and j<n2:
		if odd[i][0]<even[j]:
			out[p],out[p+1]=odd[i][0],even[j][0]
		else:
			out[p+1],out[p]=odd[i][0],even[j][0]
		i,j,p=i+1,j+1,p+1

	while i<n1:
		out[odd[i][1]]=odd[i][0]
		i=i+1
	while j<n2:
		out[even[j][1]]=even[j][0]
		j+=1
	for i in xrange(s):
		print out[i],

if __name__ == '__main__':
	main()


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1==1:
			n1+=1
		else:
			n2+=1
	if n1>0 and n2>0:
		arr.sort()
	print " ".join(map(str,arr))

if __name__ == '__main__':
	main()


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1:
			odd.append((arr[i],i))
			n1+=1
		else:
			even.append((arr[i],i))
			n2+=1

	odd.sort()
	even.sort()
	i=j=0
	out=[None]*(s)
	p=0
	while  i<n1 and j<n2:
		if odd[i][0]<even[j]:
			out[p],out[p+1]=odd[i][0],even[j][0]
		else:
			out[p+1],out[p]=odd[i][0],even[j][0]
		i,j,p=i+1,j+1,p+1
	while i<n1:
		out[odd[i][1]]=odd[i][0]
		i=i+1
	while j<n2:
		out[even[j][1]]=even[j][0]
		j+=1
	for i in xrange(s):
		print out[i],

if __name__ == '_


from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():

	s=f3()
	arr=f1()
	odd=[]
	even=[]
	n1=0
	n2=0
	for i in xrange(s):
		if arr[i]&1==1:
			odd.append((arr[i],i))
			n1+=1
		else:
			even.append((arr[i],i))
			n2+=1

	odd.sort()
	even.sort()

	if s==5516:
		print odd[:10]
		print even[:10]
	i=j=0
	out=[None]*(s)
	p=0
	while  i<n1 and j<n2:
		if odd[i][0]<even[j]:
			out[p],out[p+1]=odd[i][0],even[j][0]
		else:
			out[p+1],out[p]=odd[i][0],even[j][0]
		i,j,p=i+1,j+1,p+1

	while i<n1:
		out[odd[i][1]]=odd[i][0]
		i=i+1
	while j<n2:
		out[even[j][1]]=even[j][0]
		j+=1
	for i in xrange(s):
		print out[i],

if __name__ == '__main__':
	main()


#!/usr/bin/env pypy
from __future__ import division, print_function

import os
import sys
from __builtin__ import xrange as range
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

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

    even = any(ai % 2 == 0 for ai in a)
    odd = any(ai % 2 == 1 for ai in a)

    if even and odd:
        print(*sorted(a))
    else:
        print(*a)

# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


import fileinput
def D(a):print(a)
def S(s,I):return int(s.split(" ")[I])
def main():
    z=0
    for l in fileinput.input():
        z+=1
        if(z<2):continue;
        A=map(int,l.split(" "))
        x=0
        y=0
        for i in A:
            if(i%2==1):x=1
            if(i%2==0):y=1
        if(x==1 and y==1):A.sort()
        D(' '.join([str(v) for v in A]))
main()


n = input()
a = map(int, raw_input().split())
k = a[0] & 1
for i in range(n):
    if k != a[i] & 1:
        a.sort()
        break
print ' '.join(map(str, a))


n = input()
A = map(int, raw_input().split())

odd = []
even = []
for i in xrange(n):
    if A[i] % 2 == 0:
        even.append(A[i])
    else:
        odd.append(A[i])

ans = []
for _ in xrange(n):
    if len(odd) == 0:
        ans += even
        break
    if len(even) == 0:
        ans += odd
        break

    if odd[0] < even[0]:
        ans.append(odd.pop(0))
    else:
        ans.append(even.pop(0))

print " ".join(map(str, ans))


n = input()
A = map(int, raw_input().split())

odd = 0
even = 0

for i in xrange(n):
    if A[i] % 2 == 0:
        even += 1
    else:
        odd += 1

if odd == 0 or even == 0:
    print " ".join(map(str, A))
else:
    A.sort()
    print " ".join(map(str, A))


n = input()
a = map(int, raw_input().strip().split())

even = 0
odd = 0
for num in a:
    if num % 2 == 0:
        even = 1
    else:
        odd = 1

if even and odd:
    a.sort()

print ' '.join(map(str, a))


n = input()
a = map(int, raw_input().strip().split())

even = 0
for num in a:
    if num % 2 == 0:
        even = 1
        break

if even:
    a.sort()

print ' '.join(map(str, a))


"""
 // Author : snape_here - Susanta Mukherjee

"""
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading

# For getting input from input.txt file
#sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
#sys.stdout = open('output.txt', 'w')

def ii(): return int(input())
def fi(): return float(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())

def main():

    n=ii()
    a=li()
    s = 0
    for i in range(n):
        if  a[i] % 2:
            s+=1
    if s > 0 and s < n:
        a.sort()
        print(*a)
    else:
        print(*a)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()


n = input()
a = [int(_) for _ in raw_input().split()]
odd = [v for v in a if v%2==1]
even = [v for v in a if v%2==0]
out = []
i, j = 0, 0
while i < len(odd) or j < len(even):
    pos = []
    if i < len(odd):
        pos.append(odd[i])
    if j < len(even):
        pos.append(even[j])
    m = min(pos)
    if m%2 == 0:
        j += 1
    else:
        i += 1
    out.append(str(m))
print(' '.join(out))


n = input()
a = [int(_) for _ in raw_input().split()]
odd = [v for v in a if v%2==1]
even = [v for v in a if v%2==0]
if len(odd)*len(even):
    a.sort()
print(' '.join(map(str, a)))


#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
import heapq
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def main():
    n = int(input())
    a = [int(ai) for ai in input().split()]

    e = sorted([(i, j) for i, j in enumerate(a) if j % 2 == 0], key=lambda x: -x[1])
    o = sorted([(i, j) for i, j in enumerate(a) if j % 2], key=lambda x: -x[1])

    v = [False] * n
    sol = []

    for i, j in enumerate(a):
        f = True

        if j % 2 and e:
            k, l = e.pop()
            while v[k] and e:
                k, l = e.pop()
            if not v[k]:
                if not ((not v[i]) and (l > j)):
                    f = False
        elif (j % 2 == 0) and o:
            k, l = o.pop()
            while v[k] and o:
                k, l = o.pop()
            if not v[k]:
                if not ((not v[i]) and (l > j)):
                    f = False

        if f:
            k, l = i, j

        v[k] = True

        sol.append(l)

    print(*sol)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
import heapq
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def main():
    n = int(input())
    a = [int(ai) for ai in input().split()]

    e = sorted([(i, j) for i, j in enumerate(a) if not (j % 2)], reverse=True)
    o = sorted([(i, j) for i, j in enumerate(a) if j % 2], reverse=True)

    v = [False] * n
    sol = []

    for i, j in enumerate(a):
        f = True

        if j % 2 and e:
            k, l = e.pop()

            while v[k] and e:
                k, l = e.pop()

            if not v[k]:
                if (l > i) and (not v[i]):
                    e.append((k, l))
                else:
                    f = False
        elif j % 2 == 0 and o:
            k, l = o.pop()

            while v[k] and o:
                k, l = o.pop()

            if not v[k]:
                if (l > i) and (not v[i]):
                    o.append((k, l))
                else:
                    f = False

        if f:
            k, l = i, j

        v[k] = True
        sol.append(l)

    print(*sol)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
import heapq
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def main():
    n = int(input())
    a = [int(ai) for ai in input().split()]

    e = sorted([(i, j) for i, j in enumerate(a) if not (j % 2)], reverse=True)
    o = sorted([(i, j) for i, j in enumerate(a) if j % 2], reverse=True)

    v = [False] * n
    sol = []

    for h, i in enumerate(a):
        f = True

        if (i % 2) and e:
            j, k = e.pop()
            while v[j] and e:
                j, k = e.pop()
            if not v[j]:
                f = False
        elif (i % 2 == 0) and o:
            j, k = o.pop()
            while v[j] and o:
                j, k = o.pop()
            if not v[j]:
                f = False

        if f:
            j, k = h, i

        v[j] = True

        sol.append(k)

    print(*sol)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
import heapq
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def main():
    n = int(input())
    a = [int(ai) for ai in input().split()]

    e = []
    o = []

    for i in a:
        if i % 2:
            heapq.heappush(o, i)
        else:
            heapq.heappush(e, i)

    sol = []

    for i in a:
        j = i

        if i % 2 and e:
            j = heapq.heappop(e)
        elif (not (i % 2)) and o:
            j = heapq.heappop(o)

        sol.append(j)

    print(*sol)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
import heapq
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def main():
    n = int(input())
    a = [int(ai) for ai in input().split()]

    print(*(sorted(a) if len({i % 2 for i in a}) == 2 else a))

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()


import atexit
import io
import sys

buff = io.BytesIO()
sys.stdout = buff

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

n = input()
l = map(int, raw_input().split())
cnt1 = 0
cnt2 = 0
for a in l:
	if a&1:
		cnt1 += 1
	else:
		cnt2 += 1
if cnt1 >= 1 and cnt2 >= 1:
	l.sort()
	for a in l:
		print a,
else:
	for a in l:
		print a,


import random
import time

seed = int(time.time())
random.seed(seed)

def solve(n, xs):
    has_odd = any([x % 2 == 1 for x in xs])
    has_even = any([x % 2 == 0 for x in xs])
    if has_odd and has_even:
        sxs = sorted(xs)
        return ' '.join([str(x) for x in sxs])
    else:
        return ' '.join([str(x) for x in xs])

def main():
    n = int(raw_input().strip())
    xs = [int(x) for x in raw_input().strip().split()]
    print solve(n, xs)

if '__main__'==__name__:
    main()


#import resource
import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.Thread(target=main).start()
#threading.stack_size(2**26)
#sys.setrecursionlimit(10**6)
mod=(10**9)+7
#fact=[1]
#for i in range(1,100001):
#    fact.append((fact[-1]*i)%mod)
#ifact=[0]*100001
#ifact[100000]=pow(fact[100000],mod-2,mod)
#for i in range(100000,0,-1):
#    ifact[i-1]=(i*ifact[i])%mod
from sys import stdin, stdout
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import math
import heapq
from random import randint as rn
from Queue import Queue as Q
def find(x):
    if(x!=p[x]):
        p[x]=find(p[x])
    return p[x]
def union(x,y):
    m=find(x)
    n=find(y)
    if(m!=n):
        if(r[m]>r[n]):
            p[n]=m
        elif(r[m]<r[n]):
            p[m]=n
        else:
            p[n]=m
            r[m]+=1
def modinv(n,p):
    return pow(n,p-2,p)
def ncr(n,r,p):
    t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p
    return t
def ain():
    return map(int,sin().split())
def sin():
    return stdin.readline().strip()
def GCD(x,y):
    while(y):
        x, y = y, x % y
    return x
def isprime(x):
    if(x==1):
        return False
    elif(x<4):
        return True
    for i in range(2,int(math.sqrt(x))+1):
        if(x%i==0):
            return False
    return True
"""**************************************************************************"""
n=input()
a=ain()
s=0
for i in range(n):
    if(a[i]%2==0):
        s+=1
if(s==n or s==0):
    for i in range(n):
        stdout.write(str(a[i])+" ")
else:
    a.sort()
    for i in range(n):
        stdout.write(str(a[i])+" ")


"""
Beautiful is better than ugly.
    Explicit is better than implicit.
Simple is better than complex.
    Complex is better than complicated.
Flat is better than nested.
    Sparse is better than dense.

    * Readability counts *

 // Author : raj1307 - Raj Singh
 // Date   : 3.06.19

"""

from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p1
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

# For getting input from input.txt file
#sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
#sys.stdout = open('output.txt', 'w')

def main():

    n=ii()
    l=li()
    e=[]
    o=[]
    pe,po=-1,-1
    f=0

    for i in range(n):
        if l[i]%2==0:
            e.append(l[i])
        else:
            o.append(l[i])

    if len(e)==0 or len(o)==0:
        print(*l)
        exit()

    me=min(e)
    pe=l.index(me)
    mo=min(o)
    po=l.index(mo)
    for i in range(n):
        if l[i]%2==0:
            if l[i]>mo:
                l[i],l[po]=l[po],l[i]
                print(*l)
                exit()
        else:
            if l[i]>me:
                l[i],l[pe]=l[pe],l[i]
                print(*l)
                exit()

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()
    #dmain()