jiahuimbzuai/CoQuIR huggingface dataset:
//  [swift]
import Foundation

let N = Int(readLine()!)
var input = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }

input.sortInPlace { $0 > $1 }

var sum = 0
for i in input {
    sum += i
}

print(input)

if input[0] < sum - input[0] {
    print("Yes\n")
} else {
    print("No\n")
}
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const n = stdin.split('\n')[0]

const l = stdin.split('\n')[1].split(' ').map(Number)

const max = Math.max(...l)

const maxi = l.indexOf(max)

l.splice(maxi, 1)

const sum = l.reduce((p,c)=> p += c)

if(sum > max){
  console.log('Yes')
} else {
  console.log('No')
}
//  [typescript]
export class Main {
  static main(input: string): string {
    const [n, ls] = input.split("\n");
    const nN = Number(n);
    const lList = ls.split(" ").map(Number);
    lList.sort((a, b) => b - a);
    const max = lList[0];
    let tmp = 0;
    for (let i = 1, len = lList.length; i < len; i++) {
      tmp += lList[i];
      if (max < tmp) {
        return "Yes"
      }
    }
    return `No`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
const t={input:require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/),n:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.n())}return a}else{const a=t.input[0];t.input.shift();return Number(a)}},s:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.s())}return a}else{const a=t.input[0];t.input.shift();return String(a)}},c:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.c())}return a}else{let a=t.input[0].split('');const b=a[0];a.shift();if(a.length>0){t.input[0]=a.join('')}else{t.input.shift()}return String(b)}},o:(...arg)=>{console.log(...arg)},abs:(a)=>{return Math.abs(a)},min:(...a)=>{return Math.min(...a)},max:(...a)=>{return Math.max(...a)},floor:(a)=>{return Math.floor(a)},asc:(ar:number[])=>{return ar.sort((a,b)=>{return a-b})},desc:(ar:number[])=>{return ar.sort((a,b)=>{return b-a})},sw:(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]}};
const main=()=>{
  let n=t.n()
  let nr=t.n(n)
  let m=t.max(...nr)
  t.o(m<nr.reduce((t,d)=>{return t+d})-m?'Yes':'No')
}
main()
//  [typescript]
const main = (input: string) => {
  const lines = input.trim().split("\n");
  let L = lines[1].split(" ").map(str => parseInt(str));
  const maxLength = Math.max.apply(null, L);
  let sum = 0;

  L = L.filter(l => {
    return l !== maxLength
  })

  L.forEach(l => {
    sum += l;
  })

  console.log(sum > maxLength ? "Yes" : "No")
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const main = (input: string) => {
  const lines = input.trim().split("\n");
  const N = parseInt(lines[0])
  let L = lines[1].split(" ").map(str => parseInt(str));
  const maxLength = Math.max(...L);
  let sum = 0;
  L = L.filter(l => {
    return l !== maxLength
  })

  L.forEach(l => {
    sum += l;
  })

  console.log(sum > maxLength ? "Yes" : "No")
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const Main = args => {
  const [_, numbers] = args.split('\n');
  const number = numbers.split(' ').map(Number);
  let sum = 0;

  const max = Math.max(...number);
  const other = number.filter(num => num !== max);
  other.map(o => (sum += parseInt(o)));
  return sum <= max ? 'No' : 'Yes';
};

const args = require('fs').readFileSync('/dev/stdin', 'utf8');
console.log(Main(args))
//  [python]
N = int(input())
items = []
for i in range(N):
    s, p  = input().split()
    items.append((s, int(p), i))

items = sorted(items, key=lambda x:(x[0], -x[1]))

for s, p, i in items:
    print(i+1)
//  [python]
n = int(input())
mise = []
for i in range(n):
    name, rate = [item for item in input().split()]
    mise.append([name, -int(rate), i+1])

mise.sort()
for mise, rate, index in mise:
    print(index)
//  [python]
N = int(input())
Michelin = dict()
seen = []
number = 1
for _ in range(N):
    shop,point = map(str,input().split())
    if shop not in seen:
        Michelin[shop] = [[],[]] #moscow:{[[],[]]} point,number
        Michelin[shop][0].append(int(point)) 
        Michelin[shop][1].append(number)
        number += 1
        seen.append(shop)
    else:
        Michelin[shop][0].append(int(point))
        Michelin[shop][1].append(number)
        number += 1
seen.sort() #店の名前が辞書順になる。
#{'khabarovsk': [[20, 40], [1, 6]], 'moscow': [[10, 60], [2, 5]], 'kazan': [[50, 35], [3, 4]]}
for shop in seen:
    while Michelin[shop][0] != []:
        shokai = max(Michelin[shop][0])
        bango = Michelin[shop][0].index(shokai)
        print(Michelin[shop][1][bango])
        Michelin[shop][0].remove(shokai)
        Michelin[shop][1].remove(Michelin[shop][1][bango])
//  [python]
N = int(input())
l = []
for i in range(N):
    s,p = input().split()
    l.append([s,int(p),i+1])

l = sorted(l,key = lambda x:x[1],reverse=True)
l = sorted(l,key = lambda x:x[0])

for i in range(N):
    print(l[2])
//  [python]
n = int(input())
tbl = []
s = []
p = []
for i in range(n):
    l = list(map(str,input().split()))
    l[1] = int(l[1])
    l2 = [l[1], l[0], i + 1]
    tbl.append(l2)
    s.append(l2[1])
    p.append(l2[0])

p.sort()
p.reverse()
tbl2 = []
for i in range(n):
    for j in range(n):
        if(tbl[j][0] == p[i]):
            tbl2.append(tbl[j])
s = list(set(s))

for i in range(len(s)):
    for j in range(len(tbl2)):
        if (tbl2[j][1] == s[i]):
            print(tbl2[j][2])
//  [python]
from operator import itemgetter 
n = int(input())
point = []
ans = []
for i in range(n):
    a,b = input().split()
    s = [a,int(b),i+1]
    point.append(s)
s_point = sorted(point)
name = s_point[0][0]
for j in range(n):
    if s_point[j][0] == name:
        m = s_point[j]
        ans.append(m)
        if j == n-1:
            s_ans = sorted(ans,key=itemgetter(1),reverse=True)
            for k in range(len(ans)):
                print(s_ans[k][2])
            exit()
    else:
        s_ans = sorted(ans,key=itemgetter(1),reverse=True)
        for k in range(len(ans)):
            print(s_ans[k][2])
        ans = []
        m = s_point[j]
        ans.append(m)
        name = s_point[j][0]
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;


public class Main {
    int N;
    private class Pair implements Comparable<Pair> {
        String s;
        int p;
        int index;
        public Pair(String s, int p, int index) {
            this.s = s;
            this.p = p;
            this.index = index;
        }

        public int compareTo(Pair other) {
            if (s.equals(other.s)) {
                return other.p - this.p;
            }
            return this.s.compareTo(other.s);
        }
    }
    private void solve() {
        N = nextInt();
        ArrayList<Pair> pairs = new ArrayList<>();
        for(int i = 0;i < N;i++) {
            pairs.add(new Pair(next(), nextInt(), i));
        }

        Collections.sort(pairs);

        for(Pair pair: pairs) {
            out.println(pair.index + 1);
        }
    }

    public static void main(String[] args) {
        out.flush();
        new Main().solve();
        out.close();
    }

    /* Input */
    private static final InputStream in = System.in;
    private static final PrintWriter out = new PrintWriter(System.out);
    private final byte[] buffer = new byte[4096];
    private int p = 0;
    private int buflen = 0;

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

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

    private boolean isPrint(int ch) {
        if (ch >= '!' && ch <= '~')
            return true;
        return false;
    }

    private int nextByte() {
        if (!hasNextByte())
            return -1;
        return buffer[p++];
    }

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

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

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

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}
//  [java]
import java.util.*;

public class Main{

    void solve(){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        Restaurant[] r = new Restaurant[n];
        for(int i = 0; i < n; i++){
            r[i] = new Restaurant(scan.next(), scan.nextInt(), i + 1);
        }
        Arrays.sort(r);
        for(int i = 0; i < n; i++) System.out.println(r[i].index);
    }

    public class Restaurant implements Comparable<Restaurant>{

        String place;
        int score;
        int index;

        public Restaurant(String place, int score, int index){
            this.place = place;v
            this.score = score;
            this.index = index;
        }


        @Override
        public int compareTo(Restaurant r) {
            if(!r.place.equals(this.place)) return this.place.compareTo(r.place);
            return Integer.compare(r.score, this.score);
        }

        @Override
        public String toString(){
            return this.place + " " + this.score + " " + this.index;
        }
    }


    public static void main(String[] args){
        new Main().solve();
    }
}
//  [java]
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;


public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = Integer.parseInt(sc.nextLine());

		Map<String,Integer> lst = new TreeMap<String,Integer>();

		for (int i = 0; i < N; i++) {
			String s = sc.next();
			int pts = 100 - sc.nextInt();
			s = s + " " + String.valueOf(pts);
			lst.put(s,i+1);
		}

		for (String s : lst.keySet()) {
			System.out.println(lst.get(s));
		}

	}
}
//  [java]
import java.util.*;


public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        
        int n= sc.nextInt();
        String[] si = new String[n];
        ArrayList<String> s = new ArrayList<String>();
        int[] a = new int[n];
        
        for(int i=0; i<n; i++){
            si[i] = sc.next();
            s.add(si[i]);
            a[i] = sc.nextInt();
        }
        
        Collections.sort(s);
        int[] icount = new int[n];
        
        for(int i=0; i<n; i++){
            while(s.get(i)==s.get(i+1)){
                icount[i]++;
            }
            i++;
        }
        
        
        for(int i=0; i<n; i++){
            System.out.print(s.get(i));
            System.out.println(a[i]);
        }

        //System.out.println(ans);
        
	}
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
using lint = long long;
const lint mod = 1e9 + 7;
#define all(x) (x).begin(), (x).end()
#define bitcount(n) __builtin_popcountl((lint)(n))
#define fcout cout << fixed << setprecision(15)
#define highest(x) (63 - __builtin_clzl(x))
template<class T> inline void YES(T condition){ if(condition) cout << "YES" << endl; else cout << "NO" << endl; }
template<class T> inline void Yes(T condition){ if(condition) cout << "Yes" << endl; else cout << "No" << endl; }
template<class T = string, class U = char>int character_count(T text, U character){ int ans = 0; for(U i: text){ ans += (i == character); } return ans; }
lint power(lint base, lint exponent, lint module){ if(exponent % 2){ return power(base, exponent - 1, module) * base % module; }else if(exponent){ lint root_ans = power(base, exponent / 2, module); return root_ans * root_ans % module; }else{ return 1; }}
struct position{ int y, x; }; position mv[4] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; // double euclidean(position first, position second){ return sqrt((second.x - first.x) * (second.x - first.x) + (second.y - first.y) * (second.y - first.y)); }
template<class T, class U> string to_string(pair<T, U> x){ return to_string(x.first) + "," + to_string(x.second); } string to_string(string x){ return x; }
template<class itr> void array_output(itr start, itr goal){ string ans; for(auto i = start; i != goal; i++) ans += to_string(*i) + " "; if(!ans.empty()) ans.pop_back(); cout << ans << endl; }
template<class itr> void cins(itr first, itr last){ for(auto i = first; i != last; i++){ cin >> (*i); } }
template<class T> T gcd(T a, T b){ if(a && b){ return gcd(min(a, b), max(a, b) % min(a, b)); }else{ return a; }} template<class T> T lcm(T a, T b){ return a / gcd(a, b) * b; }
struct combination{ vector<lint> fact, inv; combination(int sz) : fact(sz + 1), inv(sz + 1){ fact[0] = 1; for(int i = 1; i <= sz; i++){ fact[i] = fact[i - 1] * i % mod; } inv[sz] = power(fact[sz], mod - 2, mod); for(int i = sz - 1; i >= 0; i--){ inv[i] = inv[i + 1] * (i + 1) % mod; } } lint C(int p, int q) const{ if(q < 0 || p < q) return 0; return (fact[p] * inv[q] % mod * inv[p - q] % mod); } };
template<class itr> bool next_sequence(itr first, itr last, int max_bound){ itr now = last; while(now != first){ now--; (*now)++; if((*now) == max_bound){ (*now) = 0; }else{ return true; } } return false; }

int main(){
    int N;
    cin >> N;
    pair<pair<string, int>, int> rest[N];
    for(int i = 0; i < N; i++){
        string S;
        int P;
        cin >> S >> P;
        rest[i] = {{S, -P}, i + 1};
    }
    sort(rest, rest + N);
    for(int i = 0; i < N; i++){
        cout << rest[i].second << endl;
    }
    
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;

#define INF 1001000100010001000
#define MOD 1000000007
#define EPS 1e-10
#define int long long
#define rep(i, N) for (int i = 0; i < N; i++)
#define Rep(i, N) for (int i = 1; i < N; i++)
#define For(i, a, b) for (int i = (a); i < (b); i++)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define vi vector<int>
#define vvi vector<vi >
#define vb vector<bool>
#define vvb vector<vb >
#define vp vector< pii >
#define all(a) (a).begin(), (a).end()
#define Int(x) int x; cin >> x;
#define int2(x, y) Int(x); Int(y);
#define int3(x, y, z) Int(x); int2(y, z);
#define in(x, a, b) ((a) <= (x) && (x) < (b))
#define fir first
#define sec second
#define ffir first.first
#define fsec first.second
#define sfir second.first
#define ssec second.second
#define Decimal fixed << setprecision(10)

//int dxy[5] = {0, 1, 0, -1, 0};
// cmd

signed main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

    Int(n);
    vector<pair<pair<string, int>, int>> data(n);
    rep(i, n) {
        cin >> data[i].ffir >> data[i].fsec;
        data[i].fsec *= -1;
        data[i].sec = i+1;
    }

    sort(all(data));

    rep(i, data.size()) {
        std::cout << data[i].sec << std::endl;
    }

    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

#define TRACE(x) x
#define WATCH(x) TRACE(cout << #x" = " << x << endl)
#define WATCHR(a, b) TRACE(for (auto it=a; it!=b;) cout << *(it++) << " "; cout << endl)
#define WATCHC(V) TRACE({cout << #V" = "; WATCHR(V.begin(), V.end());})

#define all(x) (x).begin(), (x).end()

using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vb = vector<bool>;
using vs = vector<string>;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    int N;
    cin >> N;

    vector<tuple<string, int, int>> rest(N);
    for (int i = 0; i < N; i++) {
        string city; int score;
        cin >> city >> score;
        rest[i] = make_tuple(city, -score, i);
    }

    sort(all(rest));

    for (auto p : rest) {
        cout << get<2>(p) + 1 << "\n";
    }

    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll=long long;

int main(){
 int n;
 cin >> n;
 vector<tuple<string, int,int>> t(n);
 rep(i,n){
   string s;
   int point;
   cin >> s >> point;
   t[i]=make_tuple(s,point,i+1);
 }
 sort(t.begin(),t.end());
 
 rep(i,n){
   string s;
   int point;
   int a;
   tie(s,point,a)=t[i];
   cout << a << endl;
 }
}
//  [cpp]
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll=long long;

int main(){
 int n;
 cin >> n;
 vector<tuple<string, int,int>> t(n);
 rep(i,n){
   string s;
   int point;
   cin >> s >> point;
   t[i]=make_tuple(s,point,i+1);
 }
 sort(t.begin(),t.end());
 
 rep(i,n){
   string s;
   int point;
   int a;
   tie(s,point,a)=p[i];
   cout << a << endl;
 }
}
//  [cpp]
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll=long long;

int main(){
 int n,k=0;
 cin >> n;
 vector<tuple<string, int,int>> t(n);
 rep(i,n){
   string s;
   int point;
   cin >> s >> point;
   t[i]=make_tuple(s,point,i+1);
 }
 sort(p.begin(),p.end());
 
 rep(i,n){
   string s;
   int point;
   int a;
   tie(s,point,a)=p[i];
   cout << a << endl;
 }
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
	char s[11];
	int p;
	int no;
} data;
int cmpstr(const void *x, const void *y) {
	int res = strcmp(((data *)x)->s, ((data *)y)->s);
	if (res == 0)
		return ((data *)y)->p - ((data *)x)->p;
	else
		return res;
}
int main() {
	int n;
	data d[100];
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%s%d", d[i].s, &d[i].p);
		d[i].no = i + 1;
	}
	qsort(d, n, sizeof(data), cmpstr);
	for (int i = 0; i < n; i++) {
		printf("%d\n", d[i].no);
	}
	return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>
int main(void)
{
  //Nを入力
  int n;
  scanf("%d",&n);
  //市名と点数を入力
  int i,j,k,p[n],pn[n];
  char s[n][20];
  for(i=0;i<n;i++){
    scanf("%s",&s[i]);
    scanf("%d",&p[i]);
    pn[i] = i+1;
  }
  //点数順に並び替え
  int tmp;
  char stmp[20];
  for(i=0;i<n;i++)
    for(j=i+1;j<n;j++)
      if(p[i]<p[j]){
        tmp  = p[i];
        p[i] = p[j];
        p[j] = tmp;
        tmp   = pn[i];
        pn[i] = pn[j];
        pn[j] = tmp;
        strcpy(stmp,s[i]);
        strcpy(s[i],s[j]);
        strcpy(s[j],stmp);
      }
  //辞書順に並び替え
  for(i=0;i<n-1;i++){
    for(j=n-1;j>=i+1;j--)
      if(strcmp(s[j],s[j-1])<0){
        tmp  = p[j];
        p[j] = p[j-1];
        p[j-1] = tmp;
        tmp   = pn[j];
        pn[j] = pn[j-1];
        pn[j-1] = tmp;
        strcpy(stmp,s[j]);
        strcpy(s[j],s[j-1]);
        strcpy(s[j-1],stmp);
      }
//    printf("[%d] %s %d\n",pn[i], s[i], p[i]);
  }
  for (i=0; i<n; i++) {
    printf("%d\n",pn[i]);
//  printf("[%d] %s %d\n", pn[i], s[i], p[i]);
  }
  return 0;
}
//  [c]
#include<iostream>
#include<vector>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
using ll = long long;
using P = pair<string, int>;
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>
#include<set>

int main() {
	int n;
	cin >> n;
	vector<pair<P,int>>pai;
	set<string>ss;
	rep(i, n) {
		string s;
		int p;
		cin >> s >> p;
		P pp = make_pair(s, -p);
		pai.emplace_back(make_pair(pp, i));
	}
	sort(pai.begin(), pai.end());
	rep(i, n) {
		cout << pai[i].second +1<< endl;
	}
	return 0;
}
//  [c]
#include <bits/stdc++.h>
using namespace std;
#define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

int main() {
    int N;
    cin >> N;
    vector<pair<pair<string, int>, int>> pairs;
    string s; int p;
    rep(i, N){
        cin >> s >> p;
        pairs.push_back(make_pair(make_pair(s, -p), i + 1));
    }
    sort(pairs.begin(), pairs.end());

    rep(i, N){
        cout << pairs.at(i).second << endl;
    }
}
//  [javascript]
'use strict'

const INF = 900719925474099;


function Main(input){
    let temp = input.trim().split('\n');
    let n = parseInt(temp[0])
    
    let sp = [];
    let temp2;
    for(let i=1;i<=n;i++){
        temp2 = temp[i].split(' ');
        sp.push({s:temp2[0],p:parseInt(temp2[1]),num:i})
    }
    sp.sort((a,b)=>{
        if( a.s < b.s ){
            return -1;
        }else if(a.s > b.s){
            return 1;
        }else{
            return b.p - a.p;
        }
    })
    //sp.sort((a,b)=>b.p-a.p);
    //sp.sort((a,b)=>{if(a.s<b.s){return -1}else{return 1}});
    
    let ans = [];
    for(let i=0;i<n;i++){
        ans.push(sp[i].num);
    }
    console.log(ans.join('\n'));
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const SP = arg.slice(1, N + 1);
    
    let list = [];
    
    for(let i in SP) {
        const S = SP[i].split(" ")[0];
        const P = SP[i].split(" ")[1];
        
        const temp = {name: S, point: P, originIdx: i};
        
        list.push(temp);
    }
    
    list.sort((a,b)=>{
        if(a.name < b.name) {
            return -1;
        }
        
        if(a.name > b.name) {
            return 1;
        }
        
        if(a.point - b.point > 0) {
            return -1;
        }
        
        if(a.point - b.point < 0) {
            return 1;
        }
        
        return 0;
    });
    
    // list.sort((a,b)=>a.name < b.name);
    // console.log(JSON.stringify(list));
    
    let answer = [];
    
    for(let i in list) {
        answer.push(parseInt(list[i].originIdx) + 1);
    }
    
    console.log(answer.join("\n"));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function Main(input) {
    input = input.trim().split("\n");
    var N = parseInt(input[0],10);
 
    var tmp = [];
    for(var i = 0; i < N; i++){
        tmp[i] = input[i+1].split(" ")[0] + (999 - parseInt(input[i+1].split(" ")[1],10)) + "," + (i+1);
    }
    tmp.sort();
 
    for(var i = 0; i < N; i++){
        console.log(tmp[i].split(",")[1]);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    const N = nextInt()
    let s = []
    let p = []
    let i = 0
    let r = {}
    while(hasNext()){
        i++
        let [s, p] = next().split(" ")
        if(!r[s]) r[s] = [[Number(p),i]]
        else r[s].push([Number(p), i])
    }
    let keys = Object.keys(r)
    keys.sort()
    let ans = ""
    for(let key of keys){
        let arr = r[key].sort((a,b) => b[0]-a[0])
        for(let el of arr) ans += String(el[1]) + "\n"
    }
}
Main()
//  [javascript]
'use strict'
const Main = (arg) => {
  let input = arg.trim().split('\n');
  let N = input[0].split(' ').map(Number)[0];
  // let Arr1 = input[1].split(' ').map(Number);
  let Res = [];

  // 連想配列(Dictionary)に格納
  for (let i = 1; i <= N; i++) {
    Res[i - 1] = {
      souceOrder: i,
      city: input[i].split(' ')[0],
      score: parseInt(input[i].split(' ')[1]),
      printOrder: 1
    }
  }

  // city昇順 score降順 の順に並べ替え
  Res.sort((a, b) => {
    if (a.city < b.city) return -1;
    if (a.city > b.city) return 1;
    if (a.score < b.score) return 1;
    if (a.score > b.score) return -1;
    return 0;
  });

  for (let i = 0; i < N; i++) {
    Res[i].printOrder = (i + 1);
  }
  // souceOrder昇順に並べ替え
  Res.sort((a, b) => {
    if (a.souceOrder < b.souceOrder) return -1;
    if (a.souceOrder > b.souceOrder) return 1;
    return 0;
  });

  let Ans = [];
  for (let i = 0; i < N; i++) {
    Ans.push(Res[i].printOrder);
  }

  console.log(Ans.join('\n'));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

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

const mod = 1000000007

// 1MB
const ioBufferSize = 1 * 1024 * 1024

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

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

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

type Restaurant struct {
	City  string
	Score int
	Index int
}

type Restaurants []Restaurant

func (r Restaurants) Len() int {
	return len(r)
}

func (r Restaurants) Less(i, j int) bool {
	if r[i].City != r[j].City {
		return r[i].City < r[j].City
	} else {
		return r[i].Score > r[j].Score
	}
}

func (r Restaurants) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}

func main() {
	n := nextInt()
	r := make([]Restaurant, n)

	for i := 0; i < n; i++ {
		r[i] = Restaurant{
			next(), nextInt(), i,
		}
	}

	sort.Sort(Restaurants(r))

	for _, res := range r {
		fmt.Println(res.Index + 1)
	}
}
//  [go]
package main

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

var (
	read  = bufio.NewReader(os.Stdin)
	write = bufio.NewWriter(os.Stdout)
)

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

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

func yesno(result bool) {
	if result {
		fmt.Fprintln(write, "Yes")
	} else {
		fmt.Fprintln(write, "No")
	}
}

func printansStr(result bool, a, b string) {
	if result {
		fmt.Fprintln(write, a)
	} else {
		fmt.Fprintln(write, b)
	}
}

func printansInt(result bool, a, b int) {
	if result {
		fmt.Fprintln(write, a)
	} else {
		fmt.Fprintln(write, b)
	}
}

type restaurant struct {
	name  string
	point int
	id    int
}

type rs []restaurant

func (r rs) Len() int {
	return len(r)
}

func (r rs) Less(i, j int) bool {
	if r[i].name == r[j].name {
		return r[i].point > r[j].point
	}
	return r[i].name < r[j].name
}

func (r rs) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}

func main() {
	defer write.Flush()

	var n int
	fmt.Fscan(read, &n)

	a := make(rs, n)
	for i := range a {
		a[i].id = i + 1
		fmt.Fscan(read, &a[i].name, &a[i].point)
	}

	sort.Sort(a)
	for _, r := range a {
		fmt.Fprintln(write, r.id)
	}
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

type pair struct {
	rn string
	p  int
	i  int
}

func main() {
	n := nextInt()
	s := make([]pair, n)

	for i := 0; i < n; i++ {
		s[i].rn = nextStr()
		s[i].p = nextInt()
		s[i].i = i + 1
	}

	sort.Slice(s, func(i, j int) bool {
		if s[i].f == s[j].f {
			return s[i].p > s[j].p
		}
		return s[i].rn < s[j].rn
	})

	for _, v := range s {
		fmt.Println(v.i)
	}
}

func init() {
	const max = 1024
	var buf = make([]byte, max)
	sc.Buffer(buf, max)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var name string
	var n, score int
	scanner.Scan()
	fmt.Sscan(scanner.Text(), &n)

	rests := make([]string, n)
	for i, _ := range rests {
		scanner.Scan()
		fmt.Sscan(scanner.Text(), &name, &score)
		rests[i] = fmt.Sprintf("%s %d %d", name, 101-score, i+1)
	}
	sort.Strings(rests)

	tmp := make([]string, 3)
	for _, v := range rests {
		tmp = strings.Split(v, " ")
		fmt.Println(tmp[2])
	}
}
//  [go]
package main

import (
	"fmt"
	"sort"
	"strconv"
)

func main() {
	var n, p int
	var s string
	fmt.Scan(&n)
	keys := make([]string, n)
	rsts := make(map[string]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&s, &p)
		keys[i] = s + strconv.Itoa(100-p)
		rsts[keys[i]] = i + 1
	}
	sort.Strings(keys)

	for _, k := range keys {
		fmt.Println(rsts[k])
	}
}
//  [ruby]
n = gets.to_i
sps = n.times.map { |i| [(i + 1), *gets.split] }

sps.sort_by! { |x| [x[1], -x[2].to_i] }.each do |i, _k, _v|
  puts i
end
//  [ruby]
n = gets.to_s.to_i
 
a = Array.new(n) do |i|
  s, point = gets.to_s.split
  e = s, -point.to_i, i+1
end
 
a.sort.each{|_,_,i| puts i }
//  [ruby]
n = gets.to_i
r = []
n.times do |i|
  s, p = gets.chomp.split
  r << [s, p.to_i, i + 1]
end
r.sort_by! {|s, _, _| s }
r.group_by {|s, _, _| s }.each do |_, v|
  v.sort_by! {|_, p, _| -p }
  v.each do |_, _, i|
    puts i
  end
end
//  [ruby]
n = gets.to_i
sp = []

n.times do |i|
  sp << gets.split("\s")
end

sp_dup = sp.dup

n.times do |i|
  min = [nil, nil]
  sp.each do |x|
    if !min.first || min.first > x.first
      min = x
    elsif min.first == x.first
      min = x if x.last > min.last
    end
  end
  puts sp_dup.index(sp.delete(min)) + 1
end
//  [ruby]
n = gets.to_i
sp = []
n.times do |i|
    input = gets.chomp.split
    input << i + 1
    sp << input
end
sp.sort!

orders = []
i = 0
while i < n
    count = 0

    city = sp[i][0]
    price_and_index = []
    sp.each do |arr|
        if arr.include?(city)
            count += 1
            price_and_index << [arr[1], arr[2]]
        end
    end
    price_and_index.sort!.reverse!

    order = []
    price_and_index.each do |arr|
        order << arr[1]
    end
    orders.concat(order)

    i += count
end

orders.each do |i|
    puts i
end
//  [ruby]
n=gets.to_i
a=[]
n.times{a.gets.split;a.map.with_index{|x,i|[i,x[0],x[1].to_i]}}
puts a.sort{|a,b|(a[1]<=>b[1]).nonzero?||(b[2]<=>a[2])}.map{|x|x[0]}
//  [rust]
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}



use std::cmp;
use std::iter::Iterator;

fn main() {
    input! {
      n: usize,
      sp:[(String, i32); n],
    }

    let mut vec = vec![];

    for (i,v) in sp.into_iter().enumerate(){
        vec.push((v.0, -v.1,i));
    }

    vec.sort();
    
    for elem in vec {
        println!("{}", elem.2 +1);
    }
}
//  [rust]
use std::io;
use std::collections::HashMap;
use std::cmp;

fn procon_num_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let n:i32 = procon_num_read().pop().unwrap();
	let mut s: Vec<(String, i32)> = Vec::new();
	let mut map: HashMap<(String, i32), i32> = HashMap::new();
	for i in 0..n {
		let mut buf = String::new();
		io::stdin().read_line(&mut buf).expect("");
		let mut iter = buf.split_whitespace();
		let a = iter.next().unwrap().to_string();
		let b = iter.next().unwrap().parse::<i32>().ok().unwrap();
		s.push((a, b));
	}
	for i in 0..n {
		map.insert(s[i as usize].clone(), i+1);
	}
	for i in 0..(n-1) {
		for j in (i+1)..n {
			let (a, b) = s[i as usize].clone();
			let (c, d) = s[j as usize].clone();
			match &a.cmp(&c) {
				cmp::Ordering::Greater => {
					s[i as usize] = (c, d);
					s[j as usize] = (a, b);
				},
				cmp::Ordering::Equal => {
					if d > b {
						s[i as usize] = (c, d);
						s[j as usize] = (a, b);
					}
				},
				_ => (),
			}
		}
	}
	for (a, b) in s {
		println!("{}", map.get(&(a, b)).unwrap());
	}
}
//  [rust]
use std::io::*;
use std::str::FromStr;
use std::cmp::Ordering;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char) 
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

#[derive(Eq)]
struct Shop{
    index: usize,
    name: String,
    score: u64,
}

impl PartialEq for Shop {
    fn eq(&self, other: &Shop) -> bool {
        self.name == other.name && self.score == other.score
    }
}
 
impl PartialOrd for Shop {
    fn partial_cmp(&self, other: &Shop) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Shop {
    fn cmp(&self, other: &Shop) -> Ordering{
        if self.name == other.name {
            other.score.cmp(&self.score)
        } else {
            self.name.cmp(&other.name)
        }
    }
}

fn main(){
    let n: usize = read();
    let mut s:Vec<Shop> = Vec::with_capacity(n);

    for i in 0..n {
        let e = Shop {
            index: i+1,
            name: read(),
            score: read(),
        };
        s.push(e);
    }
    s.sort();
    for e in &s{
        println!{"{}", e.index};
    }
}
//  [rust]
macro_rules! input {
     (source = $s:expr, $($r:tt)*) => {
         let mut iter = $s.split_whitespace();
         input_inner!{iter, $($r)*}
     };
     ($($r:tt)*) => {
         let s = {
             use std::io::Read;
         let mut s = String::new();
         std::io::stdin().read_to_string(&mut s).unwrap();
         s
     };
     let mut iter = s.split_whitespace();
     input_inner!{iter, $($r)*}
     };
}
     
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
 
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}
 
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
 
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
 
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
 
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
 
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{VecDeque, HashMap, BTreeMap, HashSet, BTreeSet};
#[allow(unused_imports)]
use std::io::{stdout, Write, BufWriter};
//#[allow(unused_imports)]
//use proconio::marker::{Isize1, Usize1, Bytes, Chars};
//#[proconio::fastout]
fn main() {
    input!{
        n: usize,
        sp: [(String, i32); n],
    }
    let mut btmap = BTreeMap::new();
    for (i, (s, p)) in sp.into_iter().enumerate() { btmap.entry(s).or_insert(BTreeMap::new()).insert(p, i + 1); }
    btmap.values().for_each(|rests| {
        rests.values().rev().for_each(|rest| { println!("{}", rest); })
    });
}
//  [rust]

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}


#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    ($arg:expr) => (println!("{:?}",$arg));
}


#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

use std::collections::HashMap;
use std::cmp::Ordering;


fn main() {
    input!{
        n:i32,
        restaurant : [(String , i32);n],
    }


   let mut result  = restaurant.into_iter().enumerate().map(|(i,(s,p))| (i,s,p)).collect::<Vec<_>>();
   //.map(|i,(s,u)| (i,s,u)).collect();
   result.sort_by(|r,l| {
       if r.1 != l.1 {return r.1.cmp(&l.1)}
       else{
           match r.2.cmp(&l.2) {
               Ordering::Less => {return Ordering::Greater}
               _ => {return Ordering::Less}
           }
       }
   });

    let ret = result.iter().map(|(index,a,b)| (index+1).to_string()).collect::<Vec<_>>();


   println!("{}",ret.connect("\n"));
   
   


}
//  [rust]

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}


#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    ($arg:expr) => (println!("{:?}",$arg));
}


#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

use std::collections::HashMap;
use std::cmp::Ordering;


fn main() {
    input!{
        n:i32,
        restaurant : [(String , i32);n],
    }


   let mut result  = restaurant.into_iter().enumerate().map(|(i,(s,p))| (i,s,p)).collect::<Vec<_>>();
   //.map(|i,(s,u)| (i,s,u)).collect();
   result.sort_by(|r,l| {
       if r.1 != l.1 {return r.1.cmp(&l.1)}
       else{
           match r.2.cmp(&l.2) {
               Ordering::Less => {return Ordering::Greater}
               _ => {return Ordering::Less}
           }
       }
   });

    let ret = result.iter().map(|(index,_,_)| (index+1).to_string()).collect::<Vec<_>>();


   println!("{}",ret.connect("\n"));
   
   


}
//  [swift]
let arr: [(Int, String, Int)] = (1...Int(readLine()!)!).map{
  let input = readLine()!.characters.split(" ").map{String($0)}
  return ($0, input[0], Int(input[1])!)
}
for element in arr.sort({$0.1==$1.1 ? $0.2>$1.2 : $0.1<$1.1}) {
  print(element.0)
}
//  [swift]
var arr = [(Int, String, Int)]()
for i in 1...Int(readLine()!)! {
  let input = readLine()!.characters.split(" ").map{String($0)}
  arr += [(i, input[0], Int(input[1])!)]
}
for element in arr.sort({if $0.1==$1.1{return $0.2>$1.2};return $0.1<$1.1}) {
  print(element.0)
}
//  [swift]
struct Restaurant {
  let index: Int
  let city: String
  let point: Int
}

var table: [String: [Restaurant]] = [:]

let N = Int(readLine()!)!

for i in 1...N {
  let inp = readLine()!.split(separator: " ").map { String($0) }
  table[inp[0], default: []].append(Restaurant(index: i, city: inp[0], point: Int(inp[1])!))
}
for key in table.keys.sorted() {
  for r in table[key]!.sorted { $0.point > $1.point } {
    print(r.index)
  }
}
//  [swift]
func sReadLine() -> [String] {
    return readLine()!.characters.split(" ").map{String($0)}
}
func sReadInt() -> [Int] {
    let strs = sReadLine()
    return strs.map{Int($0)!}
}
func readInt() -> Int {
    return Int(readLine()!)!
}
/************** main *****************/
var sparr: [(String, Int, Int)] = (1...n).map { i in
    let sp = sReadLine()
    return (sp[0], Int(sp[1])!, i)
}
for ssp in sparr.sort({$0.0 == $1.0 ? $0.1 > $1.1 : $0.0 < $1.0}) {
    print(ssp.2)
}
//  [swift]
func sReadLine() -> [String] {
    return readLine()!.characters.split(" ").map{String($0)}
}
func sReadInt() -> [Int] {
    let strs = sReadLine()
    return strs.map{Int($0)!}
}
func readInt() -> Int {
    return Int(readLine()!)!
}
/************** main *****************/
let n = readInt()
var sparr: [(String, Int, String)] = (1...n).map { i in
    let sp = sReadLine()
    return (sp[0], Int(sp[1])!, sp[0] + " " + sp[1])
}
for ssp in sparr.sort({$0.0 == $1.0 ? $0.1 > $1.1 : $0.0 < $1.0}) {
    print(ssp.2)
}
//  [typescript]
function Main(input) {
	const data = input.trim().split("\n");
  	const n = Number(data[0]);
  	const sps = data.slice(1).map(d => d.split(" "));
  	const sortedSps = sps.slice();
  	sortedSps.sort((a, b) => {
    	if (a[0] < b[0]) {
          return -1;
        } else if (b[0] < a[0]) {
          return 1;
        } else {
          if (Number(a[1]) < Number(b[1])) {
            return 1;
          } else {
            return -1;
          }
        }
    });
  	const result = [];
  	for (let i = 0; i < sps.length; i++) {
      const index = sps.findIndex(sp => sp[0] === sortedSps[i][0] && sp[1] === sortedSps[i][1]);
      result.push(index + 1);
    }
    console.log(result.join("\n").trim());
  	
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
'use strict'
const main = (input: string) => {
    const std: string[] = input.split('\n')
    const n: number = ~~std.shift()
    let l: string[] = std.map((v,i) => {
        const [key, val] = v.split(' ')
        // 文字列ソートなので3桁の数値になるようにしとく
        return `${key}${999 - Number(val)},${++i}`
    }).sort()
    const r = l.forEach(v => console.log(v.split(',')[1]))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim())
//  [typescript]
export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = Number(tmp[0]);
    const list: [number, string, number][] = [];
    for (let i = 1; i <= n; ++i) {
      const t: string[] = tmp[i].split(" ");
      list.push([i, t[0], Number(t[1])]);
    }
    list.sort(([n1, s1, p1], [n2, s2, p2]) => s1 < s2 ? -1 :
                                              s1 > s2 ? 1 :
                                              p2 - p1);
    return `${list.map(([i, s, p]) => i).join("\n")}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
function Main(input) {
  const lines = input.split("\n").slice(1).map((line, i) => {
    const [S, P] = line.split(' ');
    return { name: S, score: P, id: i + 1 };
  });
  lines.sort((a, b) => {
    if (a.name > b.name) {
      return 1;
    }
    else if (a.name < b.name) {
      return -1;
    }
    else {
      return b.score - a.score;
    }
  });
  lines.forEach(line => {
    console.log(line.id.toString());
  });
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
function Main(input) {
  const lines = input.split("\n").slice(1).map((line, i) => {
    const [S, P] = line.split(' ');
    return { name: S, score: P, id: i + 1 };
  });
  lines.sort((a, b) => {
    if (a.name > b.name) {
      return 1;
    }
    else if (a.name < b.name) {
      return -1;
    }
    else {
      return b.score - a.score;
    }
  });
  lines.forEach(line => {
    console.log(line.id);
  });
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [typescript]
function Main(input) {
  const lines = input.split("\n").slice(1).map((line, i) => {
    const [S, P] = line.split(' ');
    return { name: S, score: P, id: i + 1 };
  });
  lines.sort((a, b) => {
    if (a.name > b.name) {
      return 1;
    }
    else if (a.name < b.name) {
      return -1;
    }
    else {
      return b.score - a.score;
    }
  });
  const ans = lines.map(line => line.id).join('\n');
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [python]
# ABC107C - Candles (ARC101C)
def main():
    N, K, *X = map(int, open(0).read().split())
    ans = float("inf")
    for l, r in zip(X, X[K - 1 :]):
        x = r - l + min(abs(l), abs(r))
        ans = x if x < ans else ans
    print(ans)


if __name__ == "__main__":
    main()
//  [python]
import sys
input = sys.stdin.readline

def fullsearch(x, k):
    for l, r in zip(x, x[k-1:]):
        distance = abs(r - l)
        yield distance + abs(r)
        yield distance + abs(l)

def main():
    _, K = map(int, input().split())
    X = list(map(int, input().split()))



    print(min(fullsearch(X, K)))

main()
//  [python]
import sys
input = sys.stdin.readline

X = []
K = 0
def fullsearch():
    for l, r in zip(X, X[K-1:]):
        distance = abs(r - l)
        yield distance + abs(r)
        yield distance + abs(l)

def main():
    global X, K
    _, K = map(int, input().split())
    X = list(map(int, input().split()))

    print(min(fullsearch()))

main()
//  [python]

url = "https://atcoder.jp//contests/abc107/tasks/arc101_a"

def main():
    n, k = list(map(int, input().split()))
    xs = list(map(int, input().split()))
    # if xs[0] < 0 <= xs[-1]:
    #     pass
    # else:
    #     print(abs(xs[k*-1]))
    #     exit()

    ans = 100000000
    se = [0, k-1]
    while se[1] < n:
        if xs[se[0]] < 0 <= xs[se[1]]:
            tmp = min(abs(xs[se[0]]), xs[se[1]]) * 2 + max(abs(xs[se[0]]), xs[se[1]])
            ans = min(ans, tmp)
        elif xs[se[0]] < 0:
            ans = min(ans, abs(xs[se[0]]))
        elif xs[se[1]] > 0:
            ans = min(ans, xs[se[1]])
        se = [v + 1 for v in se]
    print(ans)


if __name__ == '__main__':
    main()
//  [python]

url = "https://atcoder.jp//contests/abc107/tasks/arc101_a"

def main():
    n, k = list(map(int, input().split()))
    xs = list(map(int, input().split()))
    if xs[0] < 0 <= xs[-1]:
        pass
    else:
        print(abs(xs[k*-1]))
        exit()

    ans = 100000000
    se = [0, k-1]
    while se[1] < n:
        if xs[se[0]] < 0 <= xs[se[1]]:
            tmp = min(abs(xs[se[0]]), xs[se[1]]) * 2 + max(abs(xs[se[0]]), xs[se[1]])
            ans = min(ans, tmp)
        elif xs[se[0]] < 0:
            ans = min(ans, abs(xs[se[0]]))
        elif xs[se[1]] > 0:
            ans = min(ans, xs[se[1]])
        se = [v + 1 for v in se]
    print(ans)


if __name__ == '__main__':
    main()
//  [python]
n,k = map(int,input().split())
x = list(map(int,input().split()))
ans = x[-1]-x[0]
for i in range(n-k+1):
    ans = min(ans,x[i+k-1]-x[i])
print(ans)