This repository has been archived on 2022-06-22. You can view files and clone it, but cannot push or open issues or pull requests.
usaco-guide/content/3_Bronze/6_Bronze_Pairs.md

70 lines
1.8 KiB
Markdown
Raw Normal View History

2020-06-09 15:25:25 +00:00
---
2020-06-15 23:19:07 +00:00
id: pairs
2020-06-09 15:25:25 +00:00
title: Pairs & Tuples
2020-06-15 19:44:37 +00:00
author: Aaron Chew, Benjamin Qi, Nathan Wang, Darren Yao
2020-06-09 15:25:25 +00:00
order: 6
---
2020-06-09 18:34:04 +00:00
A **pair** is a structure that holds two values, not necessarily of the same type.
2020-06-09 15:25:25 +00:00
2020-06-11 00:49:01 +00:00
(tuples?)
2020-06-09 18:34:04 +00:00
<!-- END DESCRIPTION -->
2020-06-11 00:49:01 +00:00
Of course, we can hold more than two values with something like ```pair<int,pair<int,int>>```.
2020-06-11 00:49:01 +00:00
## C++
2020-06-09 18:34:04 +00:00
2020-06-11 00:49:01 +00:00
### [Pair](http://www.cplusplus.com/reference/utility/pair/pair/)
2020-06-09 15:25:25 +00:00
- `make_pair(a, b)`: Returns a pair with values a, b.
- `pair.first`: The first value of the pair.
- `pair.second`: The second value of the pair.
Example
```cpp
#include <iostream>
using namespace std;
int main() {
pair<string, int> myPair = make_pair("Testing", 123);
cout << myPair.first << " " << myPair.second << endl; // Testing 123
vector<pair<int,int>> v = {{2,4},{1,3},{3,4},{3,1}};
sort(begin(v),end(v)); // {(1, 3), (2, 4), (3, 1), (3, 4)}
}
/* Output
* Testing 123
*/
```
2020-06-11 00:49:01 +00:00
### Tuple
(anyone use?)
## Java
2020-06-11 00:49:01 +00:00
Unfortunately there is no default class for pairs in java, so you have to create your own.
2020-06-11 00:49:01 +00:00
```java
class pair implements Comparable <pair>{
int first;
int second;
2020-06-11 00:49:01 +00:00
public int compareTo(pair other) {
return first==other.first?second-other.second:first-other.first;
}
2020-06-11 00:49:01 +00:00
pair(int a, int b) {
first=a;
second=b;
}
}
```
2020-06-11 00:49:01 +00:00
If you have an array ```pair[]arr=new pair[100]```, make sure each element of this array is not null. You can call ```Arrays.sort(arr);``` on this array and it will sort it by all the ```first``` of the array and if there is a tie in ```first``` it will sort by ```second```.
2020-06-15 19:38:13 +00:00
You can also use an `int[]` as a pair, or if you're using a pair of two different types, you can use `Object[]`.
If you want to sort by 3 or more elements, it's a simple change. Just add a new variable in ```pair``` and make sure the comparable compares in the right order you want.