結果

問題 No.1369 交換門松列・竹
ユーザー lam6er
提出日時 2025-04-15 22:04:26
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 2,598 bytes
コンパイル時間 464 ms
コンパイル使用メモリ 81,896 KB
実行使用メモリ 102,300 KB
最終ジャッジ日時 2025-04-15 22:06:13
合計ジャッジ時間 6,476 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 21 WA * 8 TLE * 1 -- * 3
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

def is_valid(a, b, c):
    if a == b or b == c or a == c:
        return False
    return (b > a and b > c) or (b < a and b < c)

def solve():
    input = sys.stdin.read().split()
    ptr = 0
    T = int(input[ptr])
    ptr += 1
    for _ in range(T):
        N = int(input[ptr])
        ptr += 1
        A = list(map(int, input[ptr:ptr+N]))
        ptr += N
        
        # Find all invalid triplets (start indices)
        S = []
        for i in range(N - 2):
            a, b, c = A[i], A[i+1], A[i+2]
            if not is_valid(a, b, c):
                S.append(i)
        
        # Collect all positions in invalid triplets
        P = set()
        for start in S:
            for j in range(start, start + 3):
                P.add(j)
        
        # Generate all candidate swaps (x, y) where x < y and A[x] != A[y]
        candidates = []
        P_list = sorted(P)
        len_p = len(P_list)
        for i in range(len_p):
            x = P_list[i]
            for j in range(i + 1, len_p):
                y = P_list[j]
                if A[x] != A[y]:
                    candidates.append((x, y))
        
        found = False
        for x, y in candidates:
            # Check if all invalid triplets are covered by x or y
            valid_coverage = True
            for start in S:
                covered = False
                for pos in [start, start + 1, start + 2]:
                    if pos == x or pos == y:
                        covered = True
                        break
                if not covered:
                    valid_coverage = False
                    break
            if not valid_coverage:
                continue
            
            # Perform swap
            A[x], A[y] = A[y], A[x]
            
            # Collect affected triplets
            affected = set()
            for pos in [x, y]:
                for s in [pos - 2, pos - 1, pos]:
                    if 0 <= s <= N - 3:
                        affected.add(s)
            
            # Check all affected triplets
            valid = True
            for s in affected:
                a, b, c = A[s], A[s+1], A[s+2]
                if not is_valid(a, b, c):
                    valid = False
                    break
            
            if valid:
                found = True
                # Undo swap before breaking
                A[x], A[y] = A[y], A[x]
                break
            
            # Undo swap
            A[x], A[y] = A[y], A[x]
        
        print("Yes" if found else "No")

if __name__ == '__main__':
    solve()
0