B. Elementary Particles

Revision en2, by witty-v, 2022-03-28 14:40:17

1625B - Elementary Particles The problem need us giving two same length sequence. Assuming the length of sequence is n. that one's index from 1 to n — 1, another from 2 to n. And two sequence at least exists one index position, make the value of same index is same and the length of sequence as large as possible.

Now that the value is same, we can enumberate the gived array, suppose a value A in array is correct answer. To find out same value B , calculating distance between B to last element in array and plus the distance between the first element to A. So we can summarize a formula. for example array = [3 1 5 2 1 3 4],

we can see the second 3 appears in behind first 3, . so first 3 is 1 and second 3 is 7 — 6 = 1, so ans = 1 + 1 = 2

we can see the second 1 appears in behind first 1, . so first 1 is 2 and second 1 is 7 — 5 = 2, so ans = 2 + 2 = 4

suppose

lenA is the length that 0 to index of A

lenB is the length that B to index of n

ans = lenA + lenB

Furthermore, in order to conveniently obtain lenA, we use array to store every element occurrence of time.

Java

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0) {
            int n = sc.nextInt();
            int nums[] = new int[2 * (int) 1e+5];
            int ans = -1;
            for (int i = 1; i <= n; i++) {
                int j = sc.nextInt();
                if (nums[j] != 0) {
                    ans = Math.max(ans, n - i + nums[j]);
                }
                nums[j] = i;
            }
            System.out.println(ans);
        }
    }

CPP

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    scanf("%d", &t);
//    cin >> t;
    while (t--) {
        int n;
        scanf("%d", &n);
        vector<int> nums(2 * 1e+5);
        int ans = -1;
        for (int i = 1; i < n + 1; ++i) {
            int j;
            scanf("%d", &j);
            if (nums[j]) {
                ans = max(ans, n - i + nums[j]);
            }
            nums[j] = i;
        }
        printf("%d\n", ans);
    }
}
Tags array, greedy

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English witty-v 2022-03-28 14:40:17 1528 (published)
en1 English witty-v 2022-03-28 14:18:21 737 Initial revision (saved to drafts)