qyliang/CodeNanoFix huggingface dataset:
You are given a simple connected graph with vertices numbered from 1 to n. Each edge connects two vertices and has a fixed integer value. Your task is to assign a positive integer to each vertex so that for every edge, the sum of the integers assigned to its two vertices equals the fixed integer value of the edge. Find the number of ways to assign these integers. The input consists of n, m, and m lines of u, v, and s values. Output the number of ways to satisfy the condition.

# Buggy version:
from collections import deque
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
G = [[] for _ in range(n+1)]
for _ in range(m):
    u, v, s = map(int, input().split())
    G[u].append((v, s))
    G[v].append((u, s))
val = [None] * (n+1)
val[1] = (1, 0)
queue = deque([1])
while queue:
    u = queue.popleft()
    for v, s in G[u]:
        if val[v]:
            continue
        val[v] = (-val[u][0], s - val[u][1])
        queue.append(v)
ma = float('inf')
mi = -float('inf')
x = -1
print(val)
for u in range(1, n+1):
    if val[u][0] == -1:
        ma = min(ma, val[u][1] - 1)
    else:
        mi = max(mi, -val[u][1] + 1)
    for v, s in G[u]:
        if val[u][0] + val[v][0] == 0:
            if val[u][1] + val[v][1] != s:
                print(0)
                exit()
        else:
            a = val[u][0] + val[v][0]
            b = s - (val[u][1] + val[v][1])
            if b % a != 0:
                print(0)
                exit()
            c = b // a
            if c <= 0:
                print(0)
                exit()
            if x == -1:
                x = c
            elif x != c:
                print(0)
                exit()
if x != -1:
    print(1)
else:
    print(max(ma - mi + 1, 0))

# Fixed version:
from collections import deque
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
G = [[] for _ in range(n+1)]
for _ in range(m):
    u, v, s = map(int, input().split())
    G[u].append((v, s))
    G[v].append((u, s))
val = [None] * (n+1)
val[1] = (1, 0)
queue = deque([1])
while queue:
    u = queue.popleft()
    for v, s in G[u]:
        if val[v]:
            continue
        val[v] = (-val[u][0], s - val[u][1])
        queue.append(v)
ma = float('inf')
mi = 1
x = -1
for u in range(1, n+1):
    if val[u][0] == -1:
        ma = min(ma, val[u][1] - 1)
    else:
        mi = max(mi, -val[u][1] + 1)
    for v, s in G[u]:
        if u > v:
            continue
        if val[u][0] + val[v][0] == 0:
            if val[u][1] + val[v][1] != s:
                print(0)
                exit()
        else:
            a = val[u][0] + val[v][0]
            b = s - (val[u][1] + val[v][1])
            if a < 0:
                b *= -1
            if b <= 0 or b % 2 == 1:
                print(0)
                exit()
            if x == -1:
                x = b // 2
            elif x != b // 2:
                print(0)
                exit()
if x != -1:
    if mi <= x <= ma:
        print(1)
    else:
        print(0)
else:
    print(max(ma - mi + 1, 0))
In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N. M bidirectional roads connect these cities. The i-th road connects City A_i and City B_i. Every road connects two distinct cities. Also, for any two cities, there is at most one road that directly connects them.

One day, it was decided that the State of Takahashi would be divided into two states, Taka and Hashi. After the division, each city in Takahashi would belong to either Taka or Hashi. It is acceptable for all the cities to belong to Taka, or for all the cities to belong Hashi. Here, the following condition should be satisfied:

Any two cities in the same state, Taka or Hashi, are directly connected by a road.

Find the minimum possible number of roads whose endpoint cities belong to the same state. If it is impossible to divide the cities into Taka and Hashi so that the condition is satisfied, print -1.

Constraints:
2 ≤ N ≤ 700
0 ≤ M ≤ N(N-1)/2
1 ≤ A_i ≤ N
1 ≤ B_i ≤ N
A_i ≠ B_i
If i ≠ j, at least one of the following holds: A_i ≠ A_j and B_i ≠ B_j.
If i ≠ j, at least one of the following holds: A_i ≠ B_j and B_i ≠ A_j.

Input:
N M
A_1 B_1
A_2 B_2
...
A_M B_M

Output:
Print the answer.

# Buggy version:
import sys
sys.setrecursionlimit(10**7)
n,m = map(int,input().split())
G = [[1]*n for i in range(n)]
for i in range(m):
  a,b = map(int,input().split())
  a -=1;b-=1
  G[a][b] = G[b][a] = 0
colors = [-1 for i in range(n)]
possible = True
ni = []
def dfs(x,y):
  colors[x] = y
  k[y] += 1
  for l in range(n):
    if l == x or G[x][l] == 0:
      continue
    if colors[l] == -1:
      dfs(l,1-y)
    elif colors[l] != 1-y:
      possible = False
for i in range(n):
  k = [0,0]
  if colors[i] != -1:
    continue
  dfs(i,0)
  ni.append([k[0],k[1]])
if possible == False:
  print(-1)
  exit()
dp =[0]*701
dp[0] = 1
for i in ni:
  for j in range(700,-1,-1):
    if dp[j]:
      dp[j+i[0]] = 1
      dp[j+i[1]] = 1
ans = float("inf")
for i in range(1,701):
  if dp[i]:
    tmp = (n-i)*(n-i-1)//2 + i*(i-1)//2
    ans = min(tmp,ans)
print(ans)

# Fixed version:
import sys
sys.setrecursionlimit(10**7)
n,m = map(int,input().split())
G = [[1]*n for i in range(n)]
for i in range(m):
  a,b = map(int,input().split())
  a -=1;b-=1
  G[a][b] = G[b][a] = 0
colors = [-1 for i in range(n)]
possible = True
ni = []
def dfs(x,y):
  colors[x] = y
  k[y] += 1
  for l in range(n):
    if l == x or G[x][l] == 0:
      continue
    if colors[l] == -1:
      dfs(l,1-y)
    elif colors[l] != 1-y:
      global possible
      possible = False
for i in range(n):
  k = [0,0]
  if colors[i] != -1:
    continue
  dfs(i,0)
  ni.append([k[0],k[1]])
if possible == False:
  print(-1)
  exit()
dp =[0]*701
dp[0] = 1
for i in ni:
  for j in range(700,-1,-1):
    if dp[j]:
      dp[j] = 0
      dp[j+i[0]] = 1
      dp[j+i[1]] = 1
ans = float("inf")
for i in range(0,701):
  if dp[i]:
    tmp = (n-i)*(n-i-1)//2 + i*(i-1)//2
    ans = min(tmp,ans)
print(ans)
Takahashi is researching sets of points in a plane. A set S of points is considered a "good set" if it satisfies two conditions: the distance between any two points in S is not √D1 and not √D2, where D1 and D2 are positive integer constants. Takahashi has proved that for any choice of D1 and D2, there exists a way to choose N^2 points from a set X of points (i, j) on a coordinate plane, where 0 ≤ i, j < 2N, so that the chosen points form a good set. The task is to find a subset of X with N^2 points that forms a good set. Constraints: 1 ≤ N ≤ 300, 1 ≤ D1 ≤ 2×10^5, 1 ≤ D2 ≤ 2×10^5, and all input values are integers. The input is given in the format N D1 D2, and the output should be N^2 distinct points that satisfy the condition. Each point (x, y) must satisfy 0 ≤ x, y < 2N and be printed in any order. If there are multiple possible solutions, any valid solution can be output.

# Buggy version:
def check_odd(i, j):
    return (i + j) % 2 == 0


def check_even(i, j):
    return i % 2 == 0


def solve(n, d1, d2):
    s1, s2 = 0, 0
    while d1 % 4 == 0:
        d1 >>= 2
        s1 += 1
    while d2 % 4 == 0:
        d2 >>= 2
        s2 += 1

    f1 = check_odd if d1 % 2 else check_even
    f2 = check_odd if d2 % 2 else check_even
    lim = n ** 2

    buf = []
    cnt = 0
    for i in range(2 * n):
        _i1 = i >> s1
        _i2 = i >> s2
        for j in range(2 * n):
            if f1(_i1, j >> s1) and f2(_i2, j >> s2):
                buf.append('{} {}'.format(i, j))
                cnt += 1
                if cnt == lim:
                    break
    return buf


n, d1, d2 = map(int, input().split())
print('\n'.join(solve(n, d1, d2)))


# Fixed version:
def check_odd(i, j):
    return (i + j) % 2 == 0


def check_even(i, j):
    return i % 2 == 0


def solve(n, d1, d2):
    s1, s2 = 0, 0
    while d1 % 4 == 0:
        d1 >>= 2
        s1 += 1
    while d2 % 4 == 0:
        d2 >>= 2
        s2 += 1

    f1 = check_odd if d1 % 2 else check_even
    f2 = check_odd if d2 % 2 else check_even
    lim = n ** 2

    buf = []
    cnt = 0
    for i in range(2 * n):
        _i1 = i >> s1
        _i2 = i >> s2
        for j in range(2 * n):
            if f1(_i1, j >> s1) and f2(_i2, j >> s2):
                buf.append('{} {}'.format(i, j))
                cnt += 1
                if cnt == lim:
                    return buf


n, d1, d2 = map(int, input().split())
print('\n'.join(solve(n, d1, d2)))

# Buggy version:
def judge(D):
  n = 0
  while D%4==0:
    n += 1
    D //= 4

  return lambda x,y: ~((x>>n)^(y>>n))&1 if D%2==1 else lambda x,y: ~(x>>n)&1

N,D1,D2 = map(int,input().split())
j1,j2 = judge(D1),judge(D2)
for _,(x,y) in zip(range(N*N),filter(lambda p: j1(*p) and j2(*p), ((x,y) for x in range(N*2) for y in range(N*2)))):
  print(x,y)

# Fixed version:
def judge(D):
  n = 0
  while D%4==0:
    n += 1
    D //= 4

  return (lambda x,y: ~((x>>n)^(y>>n))&1) if D%2==1 else (lambda x,y: ~(x>>n)&1)

N,D1,D2 = map(int,input().split())
j1,j2 = judge(D1),judge(D2)
for _,(x,y) in zip(range(N*N),filter(lambda p: j1(*p) and j2(*p), ((x,y) for x in range(N*2) for y in range(N*2)))):
  print(x,y)
You are given three integers A, B, and C, belonging to Takahashi, Nakahashi, and Hikuhashi, respectively. After performing a specific operation K times, find the difference between the integer Takahashi will have and the integer Nakahashi will have. In each operation, they simultaneously calculate the sum of the integers that the other two people have and replace their own integer with the result. If the absolute value of the answer exceeds 10^18, print "Unfair". Constraints: 1 ≤ A, B, C ≤ 10^9, 0 ≤ K ≤ 10^18. Input format: A B C K. Output the difference after K operations. If the absolute value exceeds 10^18, print "Unfair". Example: Input: 1 2 3 1, Output: 1.

# Buggy version:
A,B,C,K = map(int,input().split())
print((B - A)*(-1)**K)

# Fixed version:
A,B,C,K=map(int,input().split())
ans=(A-B)*(-1)**K
print(ans)

# Buggy version:
A,B,C,K = map(int, input().split())

if abs(A-B) > 10**(18):
    print("Unfair")
else:print(A-B)

# Fixed version:
A, B, C, K = list(map(int, input().split()))

if abs(A - B) > 10**18:
  print('Unfair')
else:
  print((A -B)*(-1)**K)

# Buggy version:
a,b,c,k=map(int,input().split())
print((a-b)*(-1)**(k-1))

# Fixed version:
a, b, c, k = map(int, input().split())
ans = (a-b)*(-1)**k
print(ans)

# Buggy version:
a,b,c,k=map(int,input().input())
print((a-b)*(-1)**k)

# Fixed version:
a,b,c,k = map(int,input().split())
print((a-b)*(-1)**k)

# Buggy version:
s=input().split()
print((int(s[0])-int(s[1]))*(-1)**s[3])

# Fixed version:
s=input().split()
print((int(s[0])-int(s[1]))*(-1)**int(s[3]))

# Buggy version:
a,b,c,k=map(int,input().split());print(-1**k*(a-b))

# Fixed version:
a,b,c,k=map(int,input().split());print((-1)**k*(a-b))

# Buggy version:
A,B,C,K=list(map(int.input().split()))
print(((-1)**K)*(A-B))

# Fixed version:
A, B, C, K = list(map(int, input().split()))
answer = (-1)**K * (A - B)
print(answer)

# Buggy version:
a,b,c,k=map(int,input().split())
if abs(a-b)<=10**18:
  print(abs(a-b))
else:
  print("Unfair")

# Fixed version:
a, b, c, k = map(int, input().split())
print((-1)**k*(a-b) if abs(a-b) <= 10**18 else "Unfair")

# Buggy version:
a,b,c,k = map(int, input().split())

x = a-b
if abs(x)>10**18:
    print('Unfair')
else:
    print(x * -1**k)


# Fixed version:
a, b, c, k = map(int ,input().split())
if abs(a-b) >10**18:
    print('Unfair')
else:
    print((a-b)*(-1)**k)
Title: Problem I: 11224111122411

A person's arm is stuck and can't be pulled out. While trying to retrieve something that rolled under a desk, they accidentally got their arm stuck and can't move it without pain. They consider calling for help but realize no one is around. They decide to use their phone to send a message for help. However, the phone's input method has a unique behavior where pressing a number key multiple times can result in different characters based on the time intervals between presses. The task is to determine the number of possible interpretations of the sent message. The input consists of multiple cases, each containing a string of numbers. The output should be the interpretation of the message modulo 100000007. The input ends with a line containing only "#". The problem is from The University of Aizu Programming Contest 2011 Summer.

# Buggy version:
def f3(n):
    a=b=c=0
    for _ in range(n):
        a,b,c=(a+b+c+1)%100000007,a,b
    return a
    
def f5(n):
    a=b=c=d=e=0
    for _ in range(n):
        a,b,c,d,e=(a+b+c+d+e+1)%100000007,a,b,c,d
    return a

while 1:
    s=input()
    if s=="#":break
    ans=1
    num="_"
    cnt=1
    for n in s+"_":
        if n==num:
            cnt+=1
        else:
            if num in "80":
                ans*=f3(cnt)
            else:
                ans*=f5(cnt)
            num=n
            cnt=1
    print(ans)


# Fixed version:
def f3(n):
    a=b=c=0
    for _ in range(n):
        a,b,c=(a+b+c+1)%100000007,a,b
    return a
    
def f5(n):
    a=b=c=d=e=0
    for _ in range(n):
        a,b,c,d,e=(a+b+c+d+e+1)%100000007,a,b,c,d
    return a

while 1:
    s=input()
    if s=="#":break
    ans=1
    num="_"
    cnt=1
    for n in s+"_":
        if n==num:
            cnt+=1
        else:
            if num in "80":
                ans=ans*f3(cnt)%100000007
            else:
                ans=ans*f5(cnt)%100000007
            num=n
            cnt=1
    print(ans)
Area of Polygons

Polygons are fundamental in geometric processing. Complex figures are often represented and handled as polygons with many short sides. If interested in geometric data processing, try programming exercises about basic polygon operations.

Your task is to write a program that computes the area of polygons.

A polygon is represented by a sequence of points, its vertices. Given vertices p1, p2, ..., pn, line segments connecting pi and pi+1 (1 <= i <= n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon.

Assume the polygon is not degenerate. No point occurs as a vertex more than once. Two sides can intersect only at a common endpoint (vertex). The polygon has at least 3 vertices. Note that the polygon is not necessarily convex; an inner angle may be larger than 180 degrees.

Input
The input contains multiple data sets, each representing a polygon. A data set is given in the format:
n
x1 y1
x2 y2
...
xn yn

The first integer n is the number of vertices, such that 3 <= n <= 50. The coordinate of a vertex pi is given by (xi, yi). xi and yi are integers between 0 and 1000 inclusive. The coordinates of vertices are given in the order of clockwise visit of them. The end of input is indicated by a data set with 0 as the value of n.

Output
For each data set, the program should output its sequence number and the area of the polygon separated by a single space. The area should be printed with one digit to the right of the decimal point. The sequence number and the area should be printed on the same line.

Sample Input
3
1 1
3 4
6 0
7
0 0
10 10
0 20
10 30
0 40
100 40
100 0
0

Output for the Sample Input
1 8.5
2 3800.0

# Buggy version:
while 1:
    n=int(input())
    if n==0:break
    p=[complex(*map(int,input().split())) for _ in range(n)]
    s,pre=0,p[0]
    while p:
        now=p.pop()
        s+=now.real*pre.imag-now.imag*pre.real
        pre=now
    print(abs(s)/2);input()

# Fixed version:
c=0
while 1:
    n=int(input())
    if n==0:break
    c+=1
    p=[complex(*map(int,input().split())) for _ in range(n)]
    s,pre=0,p[0]
    while p:
        now=p.pop()
        s+=now.real*pre.imag-now.imag*pre.real
        pre=now
    print(c,abs(s)/2);input()
Title: Get Many Persimmon Trees

Seiji Hayashi, a professor at the Nisshinkan Samurai School in the 18th century, is rewarded with a rectangular estate within a large field in the Aizu Basin by Katanobu Matsudaira, the lord of the domain of Aizu. The estate's size is specified, but its location within the field is not. The field contains many Japanese persimmon trees, known as 'Mishirazu Persimmon', a famous product of the Aizu region. Hayashi, a fan of persimmons, aims to maximize the number of persimmon trees within the estate.

Given the dimensions of the field and the coordinates of the persimmon trees, the task is to find the estate of a given size (width and height) that contains the largest number of persimmon trees.

Input:
- The input consists of multiple data sets.
- Each data set includes the number of persimmon trees, the width and height of the field, coordinates of the persimmon trees, and the width and height of the estate.

Output:
- For each data set, output the maximum possible number of persimmon trees that can be included in an estate of the given size.

Sample Input:
- Provided sample input data.

Sample Output:
- Corresponding output for the sample input.

# Buggy version:
while True:
    N = int(input())
    if N == 0: break
    W,H = map(int,input().split())
    fld = [[0 for w in range(W)] for h in range(H)]
    for i in range(N):
        x,y = map(lambda s:int(s)-1,raw_input().split())
        fld[y][x] = 1
    cums = [[0 for w in range(W+1)] for h in range(H+1)]
    for y in range(H):
        for x in range(W):
            cums[y+1][x+1] = fld[y][x] + cums[y][x+1] + cums[y+1][x] - cums[y][x]
    S,T = map(int,input().split())
    ans = 0
    for y in range(H-T+1):
        for x in range(W-S+1):
            ans = max(ans, cums[y+T][x+S] - cums[y+T][x] - cums[y][x+S] + cums[y][x])
    print(ans)

# Fixed version:
while True:
    N = int(input())
    if N == 0: break
    W,H = map(int,input().split())
    fld = [[0 for w in range(W)] for h in range(H)]
    for i in range(N):
        x,y = map(lambda s:int(s)-1,input().split())
        fld[y][x] = 1
    cums = [[0 for w in range(W+1)] for h in range(H+1)]
    for y in range(H):
        for x in range(W):
            cums[y+1][x+1] = fld[y][x] + cums[y][x+1] + cums[y+1][x] - cums[y][x]
    S,T = map(int,input().split())
    ans = 0
    for y in range(H-T+1):
        for x in range(W-S+1):
            ans = max(ans, cums[y+T][x+S] - cums[y+T][x] - cums[y][x+S] + cums[y][x])
    print(ans)
Problem C: Numeral System

Prof. Hachioji has created a new numeral system using four lowercase letters "m", "c", "x", "i" and eight digits "2", "3", "4", "5", "6", "7", "8", "9". The system excludes the digits "0" and "1". Each letter corresponds to a specific value: "m" = 1000, "c" = 100, "x" = 10, and "i" = 1. The digits "2" to "9" correspond to their respective values. This system is unrelated to the Roman numeral system.

For example, the strings "5m2c3x4i", "m2c4i", and "5m2c3x" correspond to the integral numbers 5234, 1204, and 5230, respectively. Each letter may be prefixed by a digit from "2" to "9", forming a pair where the prefix digit multiplies the value of the letter. The letters "m", "c", "x", and "i" must appear in that order from left to right, and when a digit exists in a string, it should appear as the prefix digit of the following letter. An MCXI-string corresponds to a positive integer, and each integer from 1 to 9999 has a unique MCXI-string.

Your task is to write a program that reads two MCXI-strings, computes the sum of their MCXI-values, and prints the MCXI-string corresponding to the result.

Input:
The first line contains a positive integer n (<= 500) indicating the number of following lines. Each of the next n lines contains two MCXI-strings separated by a space.

Output:
For each specification, your program should print an MCXI-string in a line. Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in the specification. No other characters should appear in the output.

# Buggy version:
a={'m':1000,'c':100,'x':10,'i':1}
for _ in range(int(input())):
    b,s,t=input(),0,1
    for x in b:
        if x==' ':continue
        if x in a:s+=a[x]*t;t=1
        else:t=int(x)
    ans=''
    for k in ['m','c','x','i']:
        c,s=divmod(s,a[k])
        if c:ans+=['',str(c)][c!=0]+k
    print(ans)

# Fixed version:
a={'m':1000,'c':100,'x':10,'i':1}
for _ in range(int(input())):
    b,s,t=input(),0,1
    for x in b:
        if x==' ':continue
        if x in a:s+=a[x]*t;t=1
        else:t=int(x)
    ans=''
    for k in ['m','c','x','i']:
        c,s=divmod(s,a[k])
        if c:ans+=['',str(c)][c!=1]+k
    print(ans)
Problem A: Dirichlet's Theorem on Arithmetic Progressions

Good evening, contestants.

If "a" and "d" are relatively prime positive integers, the arithmetic sequence beginning with "a" and increasing by "d" contains infinitely many prime numbers. This is known as Dirichlet's Theorem on Arithmetic Progressions, conjectured by Johann Carl Friedrich Gauss and proved by Johann Peter Gustav Lejeune Dirichlet in 1837.

Your mission is to write a program to find the "n"th prime number in this arithmetic sequence for given positive integers "a", "d", and "n".

Input:
The input is a sequence of datasets. Each dataset is a line containing three positive integers "a", "d", and "n" separated by a space. "a" and "d" are relatively prime. The end of the input is indicated by a line containing three zeros separated by a space.

Output:
The output should be composed of as many lines as the number of the input datasets. Each line should contain a single integer, which corresponds to the "n"th prime number among those contained in the arithmetic sequence beginning with "a" and increasing by "d". The result is always less than 10^6 under this input condition.

Sample Input:
(Provided in the original problem)

Output for the Sample Input:
(Provided in the original problem)

# Buggy version:
MAXN = 10**6
sieve = [1 for i in range(MAXN+1)]
n = 2
while n*n <= MAXN:
    if sieve[n]:
        for i in range(2*n,MAXN+1,n):
            sieve[i] = 0
    n += 1

while True:
    a,d,n = map(int,input().split())
    if n == 0: break
    cnt = 0
    for i in range(a,MAXN+1,d):
        if sieve[i]:
            cnt += 1
            if cnt == n:
                print(i)
                break

# Fixed version:
MAXN = 10**6
sieve = [0]*2 + [1]*MAXN
n = 2
while n*n <= MAXN:
    if sieve[n]:
        for i in range(2*n,MAXN+1,n):
            sieve[i] = 0
    n += 1

while True:
    a,d,n = map(int,input().split())
    if n == 0: break
    cnt = 0
    for i in range(a,MAXN+1,d):
        if sieve[i]:
            cnt += 1
            if cnt == n:
                print(i)
                break
Problem B: Organize Your Train part II

RJ Freight, a Japanese railroad company for freight operations has recently constructed exchange lines at Hazawa, Yokohama. The layout of the lines is shown in Figure B-1.

A freight train consists of 2 to 72 freight cars, denoted by 26 lowercase letters from "a" to "z". Upon arrival at the exchange lines, a train is divided into two sub-trains at an arbitrary position. Each sub-train may have its direction reversed. Finally, the two sub-trains are connected in either order to form the final configuration.

For each dataset representing an arriving train, output the number of possible train configurations.

# Buggy version:
ls = []

def add(t):
    if t not in ls:
        ls.append(t)

n = int(input())
for i in range(n):
    t = input()[:-1]
    ls = [t] 
    for j in range(1,len(t)):
        f, b = t[:j], t[j:]
        add(f+b[::-1])
        add(f[::-1]+b)
        add(f[::-1]+b[::-1])
        add(b+f)
        add(b+f[::-1])
        add(b[::-1]+f)
        add(b[::-1]+f[::-1])
    print(len(ls))

# Fixed version:
ls = []

def add(t):
    if t not in ls:
        ls.append(t)

n = int(input())
for i in range(n):
    t = input()
    ls = [t] 
    for j in range(1,len(t)):
        f, b = t[:j], t[j:]
        add(f+b[::-1])
        add(f[::-1]+b)
        add(f[::-1]+b[::-1])
        add(b+f)
        add(b+f[::-1])
        add(b[::-1]+f)
        add(b[::-1]+f[::-1])
    print(len(ls))