jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
use proconio::{fastout, input};
use std::collections::BTreeMap;

#[fastout]
fn main() {
    input! {
        n:usize,
        k:usize,
        a:[usize; n]
    }

    let mut costs = BTreeMap::new();
    let mut pos = 1;
    let mut loop_length = 0;
    let mut loop_start = 0;

    for i in 1..=k {
        pos = a[pos - 1];
        match costs.get(&pos) {
            Some(x) => {
                loop_length = i - x;
                loop_start = *x;
                break;
            }
            None => {
                costs.insert(pos, i);
            }
        }
    }

    dbg!(loop_start, loop_length);
    dbg!(&costs);
    if loop_length != 0 {
        for _ in 0..(k - loop_start) % loop_length {
            dbg!("HI");
            pos = a[pos - 1]
        }
    }

    println!("{}", pos);
}
//  [rust]
#![allow(unused_imports)]
use std::cmp::*;
use std::collections::*;
use itertools::Itertools;
use proconio::{input, marker::*, fastout};
use superslice::*;

#[fastout()]
fn main() {
    input! {
        n: usize, k: usize,
        teles: [Usize1; n],
    }

    let mut visited = vec![false; n];
    let mut before_pattern = Vec::new();
    let mut enter_pattern = Vec::new();
    let mut next = 0;

    for _ in 0..n {
        if visited[next] {
            break;
        }
        visited[next] = true;
        before_pattern.push(next);
        next = teles[next];
    }
    let mut visited = vec![false; n];
    for _ in 0..n {
        if visited[next] {
            break;
        }
        visited[next] = true;
        enter_pattern.push(next);
        next = teles[next];
    }

    if before_pattern.len() >= k+1 {
        println!("{}", before_pattern[k] + 1);
        return;
    }

    let k = k - before_pattern.len();
    let k = k % enter_pattern.len();
    println!("{}", enter_pattern[k] + 1);

    dbg!(before_pattern);
    dbg!(enter_pattern);
}
//  [swift]
/// 10
var (n,k) = cin.pair
/// [2, 3, 4, 5, 6, 4]
/// [1, 2, 3, 4, 5, 3]
let A = cin.array.map { $0-1 }
/// []
var seen = [Int]()
var seenb = (0..<n).map { _ in false }
/// 0
var current = 0

while true {
    seen.append(current)
    seenb[current] = true
    current = A[current]
    k -= 1

    if k == 0 {
        print(current+1)
        exit(0)
    }

    if seenb[current] {
        break
    }
    // if seen.contains(current) {
    //     break
    // }
}

/// seen: [0, 1, 2, 3, 4, 5]
/// current: 5
/// loop: [4, 5, 3]
/// k: 10 - 5 = 5

let loop = Array(seen[seen.firstIndex(of: current)!..<seen.count])

/// res = 5%3 = 2
/// loop[2] = 3
/// ans: 5 (index: 4)

let ans = loop[k%loop.count]
print(ans+1)

// MARK: #### 以下、ライブラリ ####

import Foundation
#if os(Linux)
    import Glibc
#else
    import Darwin.C
#endif

enum cin {
    // 123
    static var int: Int { Int(readLine()!)! }
    // 12 23
    static var pair: (Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!) }
    // 12 23 34
    static var triple: (Int, Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!, Int(line[2])!) }
    // AtCoder
    static var str: String { readLine()! }
    // At Coder
    static var arrayStr: [String] { str.components(separatedBy: " ") }
    // 1 2 3 4
    static var array: [Int] { str.components(separatedBy: " ").map { Int($0)! } }
    // 1
    // 2
    // 3
    static func v_array(count: Int) -> [Int] { (0..<count).map { _ in int } }
}

extension Int {
    // 123 -> [1, 2, 3]
    var digits: [Int] { Array(String(self)).map { Int(String($0))! } }
}

extension Array where Element == Int {
    // [2, 1, 3, 2] -> 8
    var sum: Int { self.reduce(0, +) }
    // [2, 1, 3, 2] -> [1, 2, 2, 3]
    var orderBy: [Int] { sorted() }
    // [2, 1, 3, 2] -> [3, 2, 2, 1]
    var orderByDesc: [Int] { sorted(by: { $0 > $1 }) }
    // [2, 1, 3, 2] -> [2, 1, 3]
    var distinct: [Int] { Array(Set(self)) }
}

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

extension String {
    // e.g. cin.line.regex(match: "^(dream|dreamer|erase|eraser)*$")
    func regex(match pattern: String) -> Bool {
        let regex = try! NSRegularExpression(pattern: pattern)
        return regex.firstMatch(in: self, range: NSRange(location: 0, length: self.count)) != nil
    }
    // "ABC"[1] -> "B"
    subscript(i: Int) -> Character {
        get {
            self[index(at: i)]
        }
        set(char) {
            var characters = Array(self)
            characters[i] = char
            self = String(characters)
        }
    }
    func index(at offset: Int) -> String.Index { index(startIndex, offsetBy: offset) }
    // "ABC".swapAt(0, 1) -> "BAC"
    mutating func swapAt(_ index1: Int, _ index2: Int) {
        var characters = Array(self)
        characters.swapAt(index1, index2)
        self = String(characters)
    }
}
//  [swift]
let first = readLine()!.split(separator: " ")
let N = Int(first[0])!
var K = Int(first[1])!
let steps = readLine()!.split(separator: " ").map { Int($0)! }

var chain: [Int] = []
var loopbackIndex = -1
var table: [Int: Int] = [0: 0]
var start = 0
while true {
  chain.append(start)
  let next = steps[start] - 1
  if table[next] != nil {
    loopbackIndex = table[next]!
    break
  }
  table[next] = chain.count
  start = next
}
if K < chain.count {
  print(chain[K] + 1)
} else {
  K -= chain.count
  let index = K % (chain.count - loopbackIndex)
  print(chain[loopbackIndex + index] + 1)
}
//  [swift]

let (N, K) = readLine()!.split(separator: " ").map { Int($0)! }.mapToTuple()
let As = readLine()!.split(separator: " ").map { Int($0)! }

var map = Array(repeating: [Int](), count: N)
var current = 1
var count = 0
// O(n^2)
while true {
    let hoge = As[current - 1]
    map[current - 1].append(count)
    if map[current - 1].count == 2 { break }
    current = hoge
    count += 1
}

let index = map.firstIndex(where: { $0.count == 2 })!
let (first, next) = map[index].mapToTuple()
if first <= K {
    let offset = (K - first) % (next - first)

    var result = index + 1
    // O(n)
    for _ in 0..<offset {
        result = As[result - 1]
    }
    print(result)
} else {
    print(map.firstIndex { $0.contains(K) }! + 1)
}

// MARK: -----------------------------------------------------------------------


extension Collection {
    func mapToTuple() -> (Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!, i.next()!)
    }
}

struct DP<Argument: Hashable, Element> {
    var dictionary = [Argument: Element]()
    
    var expression: (Argument, (Argument) -> Element) -> Element
    
    init(expression: @escaping (_ argument: Argument, _ note: (Argument) -> Element) -> Element) {
        self.expression = expression
    }
    
    subscript(_ argument: Argument) -> Element {
        mutating get {
            if let note = dictionary[argument] {
                return note
            } else {
                let result = expression(argument) { self[$0] }
                dictionary[argument] = result
                return result
            }
        }
    }
}
//  [python]
D = int(input())
c = list(map(int, input().split()))

s = []
for _ in range(D):
    s.append(list(map(int, input().split())))

t = []
for _ in range(D):
    t.append(int(input()))

# last(d, i)を計算するためのメモ
dp = [0] * 26


def dec(d):
    # d日の終わりに起こる満足度の減少計算の関数
    s = 0
    for j in range(26):
        s += c[j] * (d - dp[j])

    return s


# vは満足度
v = 0
for i in range(D):
    # 初日の満足度
    if (i == 0):
        v += s[i][t[i] - 1]
        # 開催されたコンテストの日付をメモ
        dp[t[i] - 1] = (i + 1)
        v -= dec(i + 1)
        print(v)
        continue

    # elif (0 < i and i < D - 1):
    v += s[i][t[i] - 1]
    dp[t[i] - 1] = (i + 1)
    v -= dec(i + 1)
    print(v)
//  [python]
# -*- coding: utf-8 -*-


def main():
    import sys
    input = sys.stdin.readline

    d = int(input())
    c = list(map(int, input().split()))
    s = [list(map(int, input().split())) for _ in range(d)]
    t = [int(input()) for _ in range(d)]
    last = [0 for _ in range(26)]
    score = 0

    for di in range(1, d + 1):
        ti = t[di - 1]
        score += s[di - 1][ti - 1]

        last[ti - 1] = di

        for j, cj in enumerate(c, 1):
            score -= cj * (di - last[j - 1])

        print(score)


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


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


def satisfaction(d, last, c):
    res = 0
    for i in range(26):
        res += c[i] * (d - last[i])
    return res


def main():
    d = I()
    c = LI()
    s = LIR(d)
    t = IR(d)
    last = [0] * 26
    satis = 0
    for day in range(d):
        j = t[day] - 1
        last[j] = day + 1
        satis += s[day][j]
        satis -= satisfaction(day + 1, last, c)
        print(satis)


main()
//  [python]
def examA():
    N = 26
    D = I()
    C = LI()
    S = [LI()for _ in range(N)]
    ans = [0]*D

    for v in ans:
        print(v)
    return

def examB():
    N = 26
    D = I()
    C = LI()
    S = [LI()for _ in range(D)]
    T = [I()for _ in range(D)]
    ans = [0]*D
    used = [0]*N
    for i,t in enumerate(T):
        ans[i] += ans[i-1]
        t -= 1
        ans[i] += S[i][t]
        used[t] = i+1
        for j in range(N):
            ans[i] -= C[j]*(i+1-used[j])
    for v in ans:
        print(v)
    return

def examC():
    ans = 0
    print(ans)
    return


from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""
//  [python]
import numpy as np
import numba


@numba.jit('i8[:](i8, i8[:], i8[:, :], i8[:])')
def solve(dd, c_arr, s_arr, t_arr):
    last_d = np.zeros(26, dtype=np.int64) - 1
    score = 0
    score_arr = np.zeros(dd, dtype=np.int64)
    for d in range(dd):
        score += s_arr[d, t_arr[d] - 1]
        last_d[t_arr[d] - 1] = d
        score -= (c_arr * (d - last_d)).sum()
        score_arr[d] = score
    return score_arr


def main():
    d = np.int64(input())
    c_arr = np.array(list(map(int, input().split()))).astype(np.int64)
    s_arr = np.array([list(map(int, input().split())) for _ in range(d)]).astype(np.int64)
    t_arr = np.array([int(input()) for _ in range(d)]).astype(np.int64)
    res = solve(d, c_arr, s_arr, t_arr)
    for r in res:
        print(r)


if __name__ == "__main__":
    main()
//  [python]
import numpy as np
import numba


@numba.njit('i4[:](i4, i4[:], i4[:, :], i4[:])')
def solve(dd, c_arr, s_arr, t_arr):
    last_d = np.zeros(26, dtype=np.int32) - 1
    score = 0
    score_arr = np.zeros(dd, dtype=np.int32)
    for d in range(dd):
        score += s_arr[d, t_arr[d] - 1]
        last_d[t_arr[d] - 1] = d
        score -= (c_arr * (d - last_d)).sum()
        score_arr[d] = score
    return score_arr


def main():
    d = np.int32(input())
    c_arr = np.array(list(map(int, input().split()))).astype(np.int32)
    s_arr = np.array([list(map(int, input().split())) for _ in range(d)]).astype(np.int32)
    t_arr = np.array([int(input()) for _ in range(d)]).astype(np.int32)
    res = solve(d, c_arr, s_arr, t_arr)
    for r in res:
        print(r)


if __name__ == "__main__":
    main()
//  [java]

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    private static int type = 26;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int d = Integer.parseInt(scan.next());
        int[] c = new int[type];
        for (int i = 0; i < type; i++) {
            c[i] = Integer.parseInt(scan.next());
        }
        int[][] s = new int[d][type];
        for (int i = 0; i < d; i++) {
            for (int j = 0; j < type; j++) {
                s[i][j] = Integer.parseInt(scan.next());
            }
        }
        int[] t = new int[d];
        for (int i = 0; i < d; i++) {
            t[i] = Integer.parseInt(scan.next());
        }
        scan.close();

        for (int i = 0; i < d; i++) {
            t[i]--;
        }
        // 前のコンテスト開催日
        int[] prevContest = new int[type];
        Arrays.fill(prevContest, -1);
        long score = 0;

        for (int i = 0; i < d; i++) {
            score += s[i][t[i]];
            prevContest[t[i]] = i;
            for (int j = 0; j < type; j++) {
                score -= c[j] * (i - prevContest[j]);
            }
            System.out.println(score);
        }
    }

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

public class Main
{
    public static void main(String[] args)
    {
        StringBuilder debug = new StringBuilder();
        Scanner sc = new Scanner(System.in);
        int period = sc.nextInt();//D
        debug.append(period+"\n");

        int[] cost = new int[26];//c
        for (int i = 0;i<cost.length;++i)
        {
            cost[i] = sc.nextInt();
            debug.append(cost[i]+" ");
        }
        debug.append("\n");

        int[][] score = new int[period][26];//s
        for (int i = 0;i<score.length;++i)
        {
            for (int j = 0;j<score[i].length;++j)
            {
                score[i][j] = sc.nextInt();
                debug.append(score[i][j]+" ");
            }
            debug.append("\n");
        }

        int[] contestTypes = new int[period];//t
        for (int i = 0;i<contestTypes.length;++i)
        {
            contestTypes[i] = sc.nextInt() - 1;
            debug.append(contestTypes[i]+"\n");
        }
        //System.err.println(debug.toString());

        Map<Integer,Integer> lastDay = new HashMap<>();//contestType,lastDay
        for (int type = 0;type < 26;++type) lastDay.put(type,0);

        long satisfaction = 0L;
        for (int date = 0;date < period;++date)
        {
            satisfaction += score[date][contestTypes[date]];
            lastDay.put(contestTypes[date],(date+1));

            long minus = 0L;
            for (int type = 0;type < 26;++type)
            {
                minus += cost[type] * ((date+1) - lastDay.get(type));
            }
            satisfaction -= minus;
            System.out.println(satisfaction);
        }
        sc.close();
    }
}
//  [cpp]
#include<stdio.h>
static inline int IN(void)
{
  int x=0,f=0,c=getchar();while(c<48||c>57){f^=c==45,c=getchar();}
  while(c>47&&c<58){x=x*10+c-48,c=getchar();}return f?-x:x;
}
int main()
{
  int c[26],D=IN(),i=0,j=0,s[365][26]={{0}},t,last[26]={0},sum=0;
  while(i<26){c[i++]=IN();}i=0;
  while(i<D){while(j<26){s[i][j++]=IN();}i++,j=0;}i=0;
  while(i<D)
  {
    j=0;t=IN()-1;sum+=s[i][t];last[t]=++i;
    while(j<26){sum-=c[j]*(i-last[j++]);}
    printf("%d\n",sum);
  }
}
//  [cpp]
#include <iostream>
using namespace std;

int c[27];
int s[366][27];
int t[366];

int last_day(int d,int type){
    int lday=0;
    for(int i=1;i<=d;i++){
        if(t[i]==type) lday=i;
    }
    
    return lday;
}

int dissatisfied(int d){
    int dis=0;
    for(int j=1;j<=26;j++){
        dis+=c[j]*(d-last_day(d,j));
    }
    return dis;
}


int solve(int d){
    int res=0;
    for(int i=1;i<=d;i++){
        res=res+s[i][t[i]]-dissatisfied(i);
    }
    return res;
}
 
 
int main(void){
    int D;cin>>D;
    
    for(int i=1;i<=26;i++){
        cin>>c[i];
    }
    
    for(int i=1;i<=D;i++){
        for(int j=1;j<=26;j++){
            cin>>s[i][j];
        }
    }
    
    for(int i=1;i<=D;i++){
        cin>>t[i];
    }
    
    for(int i=1;i<=D;i++){
        cout<<solve(i)<<endl;
    }
    
    return 0;
    
}
//  [c]
#include <stdio.h>
typedef unsigned int uint32_t;
typedef int int32_t;
typedef long long int64_t;
#define NUM_CONTESTS (26)
#define MAX_DAY (365)


int main()
{
    int32_t D;
    int32_t c[NUM_CONTESTS];
    int32_t s[MAX_DAY][NUM_CONTESTS];
    int32_t t[MAX_DAY];
    int32_t score, last[NUM_CONTESTS]={0};
    
    // Read data
    scanf("%d", &D);
    for(int i =0; i<NUM_CONTESTS;i++){
        scanf("%d", &c[i]);
    }
    for(int i=0; i<D;i++){
        for(int j=0;j<NUM_CONTESTS;j++){
            scanf("%d", &s[i][j]);
        }
    }
    for(int i=0; i<D; i++){
        scanf("%d", t+i);
    }

    // Calc satisfaction score
    for(int i=0; i<D;i++){
        int num = t[i]-1;
        score += s[i][num];
        last[num] = i+1;
        for(int j=0; j<NUM_CONTESTS; j++){
            score -= c[j]*(i+1-last[j]);
        }
        printf("%d\n",score);
    }

    
    return 0;
}
//  [c]
#include <stdio.h>

int main(){
  int d;  scanf("%d", &d);
  int c[30], s[370][30], t[370] = {0}, last[30] = {0};
  for(int i=1; i<=26; i++)  scanf("%d", c+i);
  for(int i=1; i<=d; i++)  for(int j=1; j<=26; j++)  scanf("%d", &s[i][j]);

  for(int i=1; i<=d; i++)  scanf("%d", t+i);

  long score = 0;
  for(int di=1; di<=d; di++){
    score = score + s[di][t[di]];
    last[t[di]] = di;
    for(int li=1; li<=26; li++)
      score = score - c[li]*(di-last[li]);
    printf("%ld\n", score);
  }


  return 0;
}
//  [c]
#include <stdio.h>

int main(){
  int D;
  int c[30];
  int s[370][30];
  int t[400];
  int last[30]={};
  int ans=0;
  
  scanf("%d",&D);
  for(int i=1;i<=26;i++)
    last[i]=0;
  for(int i=1;i<=26;i++)
    scanf("%d",c+i);
  for(int i=1;i<=D;i++)
   for(int j=1;j<=26;j++)
     scanf("%d",&s[i][j]);
  for(int i=1;i<=D;i++)
    scanf("%d",t+i);
  for(int d=1;d<=D;d++){
    ans+=s[d][t[d]];
    last[t[d]]=d;
    for(int j=1;j<=26;j++){
      ans-=c[j]*(d-last[j]);
    }
    printf("%d\n",ans);
  }
  
  return 0;
}
//  [c]
#include <stdio.h>

int main(void) {
	int D;
	scanf("%d",&D);
	int c[26];
	int s[D][26];
	int t[D];
	int v[D];
	int dissatisfaction=0, last;
	int ds[D];
	for(int i=0;i<26;i++) {
		scanf("%d",&c[i]);
	}
	for(int i=0;i<D;i++){
		for(int j=0;j<26;j++){
			scanf("%d",&s[i][j]);
		}
	}
	for(int i=0;i<D;i++){
		scanf("%d",&t[i]);
	}
	for(int j=0;j<D;j++) {
		for(int i=0;i<26;i++){
			int k=j;
			while(k>=0 && t[k]!=i+1) k--;
			last = k+1;
			dissatisfaction += c[i]*((j+1)-last);
		}
		ds[j] = dissatisfaction;
		dissatisfaction = 0;
	}
	v[0] = s[0][t[0]-1]-ds[0];
	for(int i=1;i<D;i++){
		v[i]=v[i-1]+s[i][t[i]-1]-ds[i];
	}
	for(int i=0;i<D;i++) {
		printf("%d\n",v[i]);
	}
}
//  [c]
#include <stdio.h>

int main(void)
{
	int D,c[26],i,j;
	scanf("%d",&D);
	for(i=0;i<26;i++){
		scanf("%d",&c[i]);
	}
	int s[D][26];
	for(i=0;i<D;i++){
		for(j=0;j<26;j++){
			scanf("%d",&s[i][j]);
		}
	}
	
	int v[D],t[D],score=0,day[26];
	for(i=0;i<D;i++){
		scanf("%d",&t[i]);
		t[i]--;
	}
	for(i=0;i<26;i++){
	day[i]=-1;
	}
	
	for(i=0;i<D;i++){
		score += s[i][t[i]];
		day[t[i]] = i;;
		for(j=0;j<26;j++){
			score -= c[j]*(i - day[j]);
		}
		v[i]=score;
		printf("%d\n",v[i]);
	}
	return 0;
}
//  [c]
#include <stdio.h>

int t[365]={0};

int last(int d,int i){
  for(int j=d;j>=0;j--){
    if(t[j]==i) return (j+1);
  }

  return 0;
}

int main() {
  int D=0;
  int c[26]={0};
  int s[365][26]={0};


  int v[365]={0};

  scanf("%d",&D);
  for(int i=0;i<26;i++) scanf("%d",&c[i]);
  for(int i=0;i<D*26;i++) scanf("%d",&s[i/26][i%26]);
  for(int i=0;i<D;i++) scanf("%d",&t[i]);

  for(int i=0;i<D;i++){
    if(i != 0) v[i] += v[i-1];

    v[i] += s[i][t[i]-1];
    
    for(int j=0;j<26;j++){
      v[i] -= c[j] * ((i+1)-last(i,j+1));
    }

    printf("%d\n",v[i]);
  }

  return 0;
}
//  [javascript]
var toInt = x=>parseInt(x,10);
var toIntArr = arr=>arr.map(x=>toInt(x));
var abs = x=>x>0?x:-x;
function min(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]<val)val = rest[i];return val}
function max(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]>val)val = rest[i];return val}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
 
function Main(input){
	var input = input.split('\n');
	input = input.map(e => toIntArr(e.split(' ')));
	var d = input[0][0];
	var cs = input[1];
	var ss = input.slice(2);
	var ts = input.slice(d+2).map(e=>e[0]);
	
	var score = 0;
	var ans = '';
	let type;
	let lastday = [];
	lastday.length = 26;
	lastday.fill(-1);

	let scoreDay = [];

	for(let i = 0; i < d; i++){
		type = ts[i];
		//console.log(ss[i][type-1])
		score += ss[i][type-1];
		lastday[type-1] = i;
		for(let j = 0; j < 26; j++){
			//console.log(cs[j] * (i - lastday[j]))
			score -= cs[j] * (i - lastday[j]);
		}

		scoreDay[i] = score;

	}

	console.log(scoreDay.join('\n'));
}
//  [javascript]
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var score = 0;
var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  const d = next();//365
  const n = 26;
  const c = nexts(n);
  const s = nextm(d,n);
  var a = xArray(0,n);
  for(var i = 0; i < d; i++){
    var t = next();
    for(var j = 0; j < n; j++){
      a[j] -= c[j];
    }
    a[t-1] = 0;
    score += s[i][t-1];
    for(var j = 0; j < n; j++)score += a[j];
    console.log(score);
  }
}
//  [javascript]
'use strict';

function Main(input) {
    const tmp = input.trim().split('\n');
    const D = Number(tmp[0]);
    const C = tmp[1].split(' ').map((v) => Number(v));
    const S = tmp
        .slice(2, 2 + D)
        .map((v) => v.split(' ').map((v) => Number(v)));
    const T = tmp.slice(-1 * D).map((v) => Number(v));

    let LastContestDays = Array(26).fill(0); // コンテストの種類ごとの最終開催日
    let currnetContestLebels = Array(26).fill(0); // ある開催日のコンテストごとの満足度
    let lebel = 0; // 満足度の累計

    for (let i = 1; i <= D; i++) {
        LastContestDays[T[i - 1] - 1] = i;
        for (let j = 0; j < C.length; j++) {
            if (LastContestDays[j] === i) {
                currnetContestLebels[j] = S[i - 1][j];
            } else {
                currnetContestLebels[j] = C[j] * (i - LastContestDays[j]) * -1;
            }
        }
        lebel += currnetContestLebels.reduce((acc, cur) => acc + cur);
        console.log(String(lebel));
    }

    return;
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

const n = 26

func main() {
	io := NewIo(os.Stdin, os.Stdout)
	defer io.Flush()
	d := io.NextInt()
	c := io.NextInts(n)
	s := make([][]int, d)
	for i := 0; i < d; i++ {
		s[i] = io.NextInts(n)
	}
	t := io.NextInts(d)
	ans := solve(c, s, t)
	for i := range ans {
		io.Println(ans[i])
	}
}

func solve(c []int, s [][]int, t []int) []int {
	d := len(s)
	lasts := make([]int, n)
	scores := make([]int, d+1)
	for i := 0; i < d; i++ {
		lasts[t[i]-1] = i + 1
		up := s[i][t[i]-1]
		down := calcDown(c, lasts, i+1)
		scores[i+1] = scores[i] + up - down
	}
	return scores[1:]
}

func calcDown(c []int, lasts []int, day int) int {
	down := 0
	for i := 0; i < n; i++ {
		down += c[i] * (day - lasts[i])
	}
	return down
}

// Io is I/O object
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

// NewIo returns a new Io instance
func NewIo(r io.Reader, w io.Writer) *Io {
	return &Io{
		reader: bufio.NewReader(r),
		writer: bufio.NewWriter(w),
	}
}

// Flush flushes writer
func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

// NextLine scans a line from stdin
func (io *Io) NextLine() string {
	var buffer []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

// Next return a word from stdin
func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

// NextInt returns an integer from stdin
func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

// NextInts returns n integers from stdin
func (io *Io) NextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = io.NextInt()
	}
	return ret
}

// Println is a wrapper of fmt.Fprintln
func (io *Io) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}
//  [go]
package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

func getInts(N int) []int {
	ret := make([]int, N)
	for i := 0; i < N; i++ {
		ret[i] = getInt()
	}
	return ret
}

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

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func calcScore(day int, score, c, last []int) int {
	loss := make([]int, 26)
	for i := 0; i < 26; i++ {
		loss[i] = c[i] * (day - last[i])
	}

	ret := 0
	for j := 0; j < 26; j++ {
		score[j] -= loss[j]
		ret += score[j]
	}

	return ret
}

func main() {
	sc.Split(bufio.ScanWords)
	D := getInt()
	c := getInts(26)
	s := make([][]int, D)
	for i := 0; i < D; i++ {
		s[i] = getInts(26)
	}

	last := make([]int, 26)
	score := make([]int, 26)

	for i := 0; i < D; i++ {
		t := getInt() - 1
		score[t] += s[i][t]
		last[t] = i + 1
		ans := calcScore(i+1, score, c, last)
		out(ans)
		// out(score)
	}

	// for i := 0; i < D; i++ {
	// 	maxS := 0
	// 	idxS := 0
	// 	for j := 0; j < 26; j++ {
	// 		if maxS < s[i][j] {
	// 			maxS = s[i][j]
	// 			idxS = j
	// 		}
	// 	}
	// 	out(idxS + 1)
	// }
}
//  [go]
package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wt = bufio.NewWriter(os.Stdout)
)

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

func nextInt() int {
	i, _ := strconv.Atoi(next())
	return i
}

func nextInts(n int) []int {
	slice := make([]int, n)
	for i := 0; i < n; i++ {
		slice[i] = nextInt()
	}
	return slice
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	D := nextInt()
	c := nextInts(26)
	s := make([][]int, D)
	for i := range s {
		s[i] = nextInts(26)
	}

	last := [26]int{}
	v := 0
	for d := 0; d < D; d++ {
		t := nextInt() - 1
		last[t] = d + 1

		v += s[d][t]
		dec := 0
		for i := 0; i < 26; i++ {
			dec += c[i] * (d + 1 - last[i])
		}
		v -= dec

		puts(v)
	}
}
//  [go]
package main

import "fmt"

func main() {
	var D int
	fmt.Scan(&D)
	cs := make([]int, 26)
	for i := 0; i < 26; i++ {
		fmt.Scan(&cs[i])
	}

	ss := make([][26]int, D)
	for d := 0; d < D; d++ {
		for i := 0; i < 26; i++ {
			fmt.Scan(&ss[d][i])
		}
	}

	ts := make([]int, D)
	for i := 0; i < D; i++ {
		fmt.Scan(&ts[i])
	}

	last := [26]int{}
	sat := 0
	for d := 0; d < D; d++ {
		j := ts[d] - 1
		last[j] = d + 1
		for i := 0; i < 26; i++ {
			sat -= (d + 1 - last[i]) * cs[i]
		}
		sat += ss[d][j]
		fmt.Println(sat)
	}
}
//  [go]
package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	return sc
}

func main() {
	sc = initScanner(os.Stdin)
	resolve(parseProblem())
}

func parseProblem() scorer {
	d := scanInt(sc)
	v := 26
	cs := make([]int, v)
	for i := 0; i < v; i++ {
		cs[i] = scanInt(sc)
	}
	ss := make([][]int, d)
	for i := range loop0(d) {
		ss[i] = make([]int, v)
		for j := range loop0(v) {
			ss[i][j] = scanInt(sc)
		}
	}
	return scorer{
		d: d, v: v,
		cs: cs, ss: ss,
	}
}

type scorer struct {
	// 0-indexed
	d, v int
	cs   []int
	ss   [][]int // [<d][<v]
}

func (scr scorer) receiveInput(sc *bufio.Scanner) []int {
	satisfaction := 0
	lasts := make([]int, scr.v)
	results := make([]int, scr.d)
	for day := range loop0(scr.d) {
		tipe := scanInt(sc) - 1
		satisfaction += scr.ss[day][tipe]
		lasts[tipe] = day + 1
		for cType := range loop0(scr.v) {
			satisfaction -= scr.cs[cType] * (day + 1 - lasts[cType])
		}
		results[day] = satisfaction
	}
	return results
}

func loop0(n int) chan int {
	return loop(0, n-1, 1)
}

func loop1(n int) chan int {
	return loop(1, n, 1)
}

func loop(s, e, d int) chan int {
	ch := make(chan int)
	go func() {
		for i := s; i <= e; i += d {
			ch <- i
		}
		close(ch)
	}()
	return ch
}

func resolve(scor scorer) {
	for _, r := range scor.receiveInput(sc) {
		fmt.Println(r)
	}
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

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

func main() {
	D := ReadInt()
	cs := ReadInts(26)
	ss := make([][]int, D)
	for i := 0; i < D; i++ {
		ss[i] = ReadInts(26)
	}
	ts := ReadInts(D)

	score := 0
	last := make([]int, 26)
	for d := 1; d <= D; d++ {
		t := ts[d-1] - 1
		score += ss[d-1][t]
		last[t] = d
		for i := 0; i < 26; i++ {
			score -= cs[i] * (d - last[i])
		}
		fmt.Println(score)
	}
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int) { Scan(&i); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}
//  [ruby]
days = gets.to_i
c = gets.split(" ").map(&:to_i).slice(0,26)
s = Array.new(days).map{|d| gets.split(" ").map(&:to_i).slice(0,26)}
t = Array.new(days).map{|d| gets.to_i }
last = Array.new(26,0)


score = 0


for d in 1..days
    i = t[d-1] - 1   #イベント種別
    score += s[d-1][i]
    last[i] = d
    c.each_with_index do |rate, index|
        score = score - rate * (d - last[index])
    end
    puts score
end
//  [ruby]
N = 26
D = gets.to_i
C = Array.new(N + 1, 0)
S = Array.new(D + 1){ Array.new(N + 1, 0) }

gets.split.map(&:to_i).each_with_index do |c, i|
  C[i + 1] = c
end

D.times do |i|
  gets.split.map(&:to_i).each_with_index do |s, j|
    S[i + 1][j + 1] = s
  end
end

def score(ans)
  last = Array.new(N + 1, 0)
  s = 0
  scores = Array.new(D + 1, 0)
  (1 .. D).each do |d|
    c = ans[d]
    last[c] = d
    s += S[d][c]
    (1 .. N).each do |c_|
      s += C[c_] * (last[c_] - d)
    end
    scores[d] = s
  end
  scores
end


A = Array.new(D + 1, 0)
(1 .. D).each do |d|
  A[d] = gets.to_i
end


puts score(A)[1,D]
//  [ruby]
lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

D = lines[0][0]

class Array
  def max_id
    max = - 10000000000
    tmp = -1
    for i in 1..self.length do
      if self[i-1] > max then
        tmp = i-1
        max = self[i-1]
      end
    end
    return tmp
  end
end

last_date = []
for i in 1..26 do
  last_date.push(0)
end

satis = 0
for i in 1..D do
  contest = lines[D+i+1][0]
  satis += lines[i+1][contest-1]
  last_date[contest-1] = i
  for j in 1..26 do
    satis -= (i - last_date[j-1]) * lines[1][j-1]
  end
  puts satis
end
//  [ruby]
require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
d = gets.chomp.to_i
c = gets.chomp.split.map(&:to_i)
s = []
d.times do
  s.push gets.chomp.split.map(&:to_i)
end

t = []
d.times do |i|
  t.push gets.chomp.to_i
end

score = 0
lasts = Array.new(26, 0)
d.times do |i|
  type = t[i] - 1
  score += s[i][type]
  lasts[type] = i + 1

  26.times do |j|
    score -= c[j] * (i + 1 - lasts[j])
  end
  puts score
end
//  [ruby]
#!/usr/bin/env ruby

D = gets.chomp.to_i
C = gets.chomp.split.map(&:to_i)

S = []

D.times do |i|
  S[i] = gets.chomp.split.map(&:to_i)
end

T = []

D.times do |i|
  T[i] = gets.chomp.to_i - 1
end

score = 0
last_days = Array.new(26, 0)

T.each.with_index(1) do |t, day|
  score += S[day-1][t]

  last_days[t] = day

  last_days.each_with_index do |last_day, i|
    score -= C[i] * (day - last_day)
  end

  puts score
end
//  [ruby]
D = gets.to_i
c = gets.split.map(&:to_i)
s = []
D.times do
  s << gets.split.map(&:to_i)
end

t = []
D.times do
  t << gets.to_i
end
ld = Array.new(26,0)
v = 0
(1..D).each do |day|
  sel = t[day-1] -1
  v += s[day-1][sel]
  ld[sel] = day
  26.times do |j|
    next if j == sel
    
    v -= c[j] * (day - ld[j])
  end
  puts v
end
//  [rust]
use std::io::Read;

#[allow(non_snake_case)]
struct Input {
    D: usize,          // Days
    s: Vec<Vec<i64>>,  // score(day, contest)
    c: Vec<i64>        // cost(contest)
}

fn compute_scores(input: &Input, out: &Vec<usize>) -> Vec<i64> {
    let mut scores = vec![];
    let mut score = 0;
    let mut last = vec![0; 26];
    for d in 0..out.len() {
        score += input.s[d][out[d]];
        last[out[d]] = d + 1;
        for i in 0..26 {
            score -= input.c[i] * (d + 1 - last[i]) as i64;
        }
        scores.push(score);
    }
    scores
}


#[allow(non_snake_case)]
fn main() {
    let mut buffer = String::new();
    std::io::stdin().read_to_string(&mut buffer).unwrap();
    let mut iter = buffer.split_whitespace();

    let D: usize = iter.next().unwrap().parse().unwrap();
    let c: Vec<i64> = (0..26)
        .map(|_| iter.next().unwrap().parse().unwrap()).collect();
    let s: Vec<Vec<i64>> = (0..D)
        .map(|_| (0..26)
            .map(|_| iter.next().unwrap().parse().unwrap()).collect()
        )
        .collect();
    let input = Input{ D, s, c };

    let out: Vec<usize> = (0..D)
        .map(|_| (iter.next().unwrap().parse::<i64>().unwrap() - 1) as usize).collect();

    let scores = compute_scores(&input, &out);
    for i in 0..D {
        println!("{}", scores[i]);
    }
}
//  [rust]
use std::io;
use std::collections::HashMap;

fn procon_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 score(c: &mut Vec<i64>, s: &mut Vec<Vec<i64>>, last: &mut HashMap<i64, i64>, t: &mut Vec<i64>, d:&u32){
    let mut score:i64 = 0;
    for i in 0..*d {
        let mut minusSatisfy:i64 = 0;
        last.insert(t[i as usize], (i + 1) as i64);
        for j in 1..(26+1) {
            minusSatisfy += c[(j-1) as usize]*((i+1) as i64 - *(last.get(&(j as i64)).unwrap()) );
            //println!("{}回目: minusSatisfy = {}", j, minusSatisfy);
        }
        score += s[i as usize][(t[i as usize] - 1) as usize] - minusSatisfy;
        println!("{}", score);
    }
}

fn main() {
    let mut d:u32 = procon_read()[0];
    /* c_i */
    let mut c:Vec<i64> = procon_read();
    
    /*s_{d, i}*/
    let mut s:Vec<Vec<i64>> = Vec::new();
    for i in 0..d {
        s.push(procon_read());
    }
    
    /* test schaduled*/
    let mut t:Vec<i64> = Vec::new();
    for i in 0..d {
        t.push(procon_read()[0]);
    }
    
    /*last(d, i)*/
    let mut last:HashMap<i64, i64> = HashMap::new();
    for i in 1..(26+1) {
        last.insert(i as i64, 0);
    }
    
    score(&mut c, &mut s, &mut last, &mut t, &mut d);
    
}
//  [rust]
#![allow(unused_imports, unused_macros, dead_code)]

macro_rules! loop_timeout {
    ( $sec:expr; $body:expr ) => {
        let now = std::time::SystemTime::now();
        loop {
            match now.elapsed() {
                Ok(elapsed) => {
                    if elapsed.as_secs() > $sec {
                        break;
                    }
                    $body
                }
                Err(e) => {
                    eprintln!("Err, {:?}", e);
                }
            }
        }
    };
}

macro_rules! min {
    (.. $x:expr) => {{
        let mut it = $x.iter();
        it.next().map(|z| it.fold(z, |x, y| min!(x, y)))
    }};
    ($x:expr) => ($x);
    ($x:expr, $($ys:expr),*) => {{
        let t = min!($($ys),*);
        if $x < t { $x } else { t }
    }}
}
macro_rules! max {
    (.. $x:expr) => {{
        let mut it = $x.iter();
        it.next().map(|z| it.fold(z, |x, y| max!(x, y)))
    }};
    ($x:expr) => ($x);
    ($x:expr, $($ys:expr),*) => {{
        let t = max!($($ys),*);
        if $x > t { $x } else { t }
    }}
}
macro_rules! ewriteln {
    ($($args:expr),*) => { let _ = writeln!(&mut std::io::stderr(), $($args),*); };
}
macro_rules! trace {
    ($x:expr) => { ewriteln!(">>> {} = {:?}", stringify!($x), $x) };
    ($($xs:expr),*) => { trace!(($($xs),*)) }
}
macro_rules! put {
    (.. $x:expr) => {{
        let mut it = $x.iter();
        if let Some(x) = it.next() { print!("{}", x); }
        for x in it { print!(" {}", x); }
        println!("");
    }};
    ($x:expr) => { println!("{}", $x) };
    ($x:expr, $($xs:expr),*) => { print!("{} ", $x); put!($($xs),*) }
}

const M: i64 = 1_000_000_007;

fn score(cs: &Vec<i128>, s: &Vec<Vec<i128>>, t: &Vec<usize>) -> i128 {
    let days = t.len();
    let mut r = 0;
    let mut last = vec![0; 26];
    for d in 0..days {
        let i = t[d];
        last[i] = d + 1;
        r += s[d][i];
        for i in 0..26 {
            r -= cs[i] * (d + 1 - last[i]) as i128;
        }
        put!(r);
    }
    r
}

fn main() {
    let mut sc = Scanner::new();
    let d: usize = sc.cin();
    let cs: Vec<i128> = sc.vec(26);
    let s: Vec<Vec<i128>> = (0..d).map(|_| sc.vec(26)).collect();
    let t: Vec<_> = sc.vec::<usize>(d).iter().map(|i| i - 1).collect();

    let _ = score(&cs, &s, &t);
}

use std::collections::VecDeque;
use std::io::{self, Write};
use std::str::FromStr;

struct Scanner {
    stdin: io::Stdin,
    buffer: VecDeque<String>,
}
impl Scanner {
    fn new() -> Self {
        Scanner {
            stdin: io::stdin(),
            buffer: VecDeque::new(),
        }
    }
    fn cin<T: FromStr>(&mut self) -> T {
        while self.buffer.is_empty() {
            let mut line = String::new();
            let _ = self.stdin.read_line(&mut line);
            for w in line.split_whitespace() {
                self.buffer.push_back(String::from(w));
            }
        }
        self.buffer.pop_front().unwrap().parse::<T>().ok().unwrap()
    }
    fn chars(&mut self) -> Vec<char> {
        self.cin::<String>().chars().collect()
    }
    fn vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.cin()).collect()
    }
}
//  [rust]
use proconio::{input, marker::Usize1};

const V: usize = 26;

struct State {
    cc: Vec<i32>,
    ss: Vec<Vec<i32>>,
    tt: Vec<usize>,
}

impl State {
    fn new(cc: Vec<i32>, ss: Vec<Vec<i32>>, tt: Vec<usize>) -> State {
        State { cc, ss, tt }
    }

    fn calc_score(&self) -> i32 {
        let mut score = 0;
        let mut last = vec![0; V];
        for (d, &t) in self.tt.iter().enumerate() {
            let day = d as i32 + 1;
            last[t] = day;
            score += self.ss[d][t];
            score -= last
                .iter()
                .zip(self.cc.iter())
                .map(|(&l, &c)| c * (day - l))
                .sum::<i32>();
        }
        score
    }
}

fn main() {
    input! {
        d: usize,
        cc: [i32; V],
        ss: [[i32; V]; d],
        tt: [Usize1; d],
    }
    for i in 1..=tt.len() {
        let state = State::new(cc.clone(), ss.clone(), tt[..i].to_vec());
        println!("{}", state.calc_score());
    }
}
//  [swift]
// input
let D = Int(readLine()!)!
let cs: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
let ss: [[Int]] = (1...D).map { _ in readLine()!.split(separator: " ").map { Int($0)! } }

// output
let ts: [Int] = (1...D).map { _ in Int(readLine()!)! }


func calculateSatisfactionPoint(D: Int, cs: [Int], ss: [[Int]], ts: [Int]) {
    var lastContestDate: [Int] = Array(repeating: 0, count: 26)
    var vs: [Int] = [0]
    for d in 1...D {
        let todayContestType: Int = ts[d-1]
        vs.append(vs[d-1] + ss[d-1][todayContestType-1])
        lastContestDate[todayContestType-1] = d
        
        var decreaseSatisfactionPoint: Int = 0
        for i in 0..<26 {
            decreaseSatisfactionPoint -= cs[i]*(d - lastContestDate[i])
        }
        vs[d] += decreaseSatisfactionPoint
        print(vs[d])
    }
}

calculateSatisfactionPoint(D: D, cs: cs, ss: ss, ts: ts)	// (๑•ૅㅁ•๑)
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const D = Number(input[0][0]);
  const C = input[1].map(Number);
  const S = input.slice(2, 2 + D).map((line) => line.map(Number));
  const T = input.slice(2 + D, -1).map((line) => Number(line[0]));

  let score = 0;

  const V: number[] = [];
  const L = Array(26).fill(0);

  T.forEach((t, i) => {
    L[t - 1] = i + 1;

    score += S[i][t - 1];
    score -= C.reduce((sum, c, j) => sum + c * (i + 1 - L[j]), 0);

    V.push(score);
  });

  return V.join("\n");
};

console.log(main(read()));
//  [python]
import math
MOD = 10 ** 9 + 7


def main():
    n, m = map(int, input().split())
    total =math.factorial(n+m)
    if abs(n-m) >= 2:
        return 0
    if abs(n-m) == 1:
        return math.factorial(n) * math.factorial(m) % MOD
    return math.factorial(n) * math.factorial(m) * 2 % MOD
print(main())
//  [python]
import sys

MOD = 10 ** 9 + 7
U = 10 ** 6
def make_fac_ifac(n=U, p=MOD):
  fac = [None] * (n + 1)
  fac[0] = 1
  for i in range(n): fac[i+1] = fac[i] * (i + 1) % p
  ifac = [None] * (n + 1)
  ifac[n] = pow(fac[n], p - 2, p)
  for i in range(n, 0, -1): ifac[i-1] = ifac[i] * i % p
  return fac, ifac

fac, ifac = make_fac_ifac()

def mod_choose(n, r, p=MOD):
  if r > n or r < 0: return 0
  return fac[n] * ifac[r] % p * ifac[n-r] % p

def make_choose_n_table(n=10 ** 9, r=U, p=MOD):
  table = [None] * (r + 1)
  table[0] = 1
  j = 1
  for i in range(n, n - r, -1): 
    table[j] = table[j-1] * i % p
    j += 1
  for i in range(1, r + 1): table[i] = table[i] * ifac[i] % p
  return table
    
mod_choose_n = make_choose_n_table()

n, m = map(int, sys.stdin.readline().split())

def main():
  d = abs(n - m)
  if d >= 2: res = 0
  elif d == 1: res = fac[n] * fac[m] % MOD
  else: res = fac[n] * fac[m] % MOD * 2 % MOD
  print(res)
  
if __name__ == '__main__':
  main()
//  [python]
MOD=10**9+7
class Fp(int):
    def __new__(self,x=0):return super().__new__(self,x%MOD)
    def inv(self):return self.__class__(super().__pow__(MOD-2,MOD))
    def __add__(self,value):return self.__class__(super().__add__(value))
    def __sub__(self,value):return self.__class__(super().__sub__(value))
    def __mul__(self,value):return self.__class__(super().__mul__(value))
    def __floordiv__(self,value):return self.__class__(self*self.__class__(value).inv())
    def __pow__(self,value):return self.__class__(super().__pow__(value%(MOD-1), MOD))
    __radd__=__add__
    __rmul__=__mul__
    def __rsub__(self,value):return self.__class__(-super().__sub__(value))
    def __rfloordiv__(self,value):return self.__class__(self.inv()*value)
    def __iadd__(self,value):self=self+value;return self
    def __isub__(self,value):self=self-value;return self
    def __imul__(self,value):self=self*value;return self
    def __ifloordiv__(self,value):self=self//value;return self
    def __ipow__(self,value):self=self**value;return self
    def __neg__(self):return self.__class__(super().__neg__())

class Combination:
    def __init__(self,max_n):
        self.max_n=0
        self.fact=[Fp(1)]
        self.ifact=[Fp(1)]
        self.make_fact_list(max_n)
    def C(self,n,k):return self.fact[n]*self.ifact[k]*self.ifact[n-k] if 0<=k<=n else 0
    def H(self,n,k):return self.C(n+k-1,k) if n or k else 1
    def P(self,n,k):return self.fact[n]*self.ifact[n-k] if 0<=k<=n else 0
    def make_fact_list(self,max_n):
        if max_n<=self.max_n: return
        self.fact+=[Fp(0)]*(max_n-self.max_n)
        self.ifact+=[Fp(0)]*(max_n-self.max_n)
        for i in range(self.max_n+1,max_n+1):
            self.fact[i]=self.fact[i-1]*i
            self.ifact[i]=self.ifact[i-1]//i
        self.max_n=max_n

N, M = sorted(map(int, input().split()))
p = Combination(M)
ans = p.fact[N]*p.fact[M]
if N == M:
    ans *= 2
if abs(N-M) > 1:
    ans = 0
print(ans)
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;

public class Main {
	public static int mod= (int) (1e9+7);
	public static void main(String[] args) throws IOException {
		FastScanner in = new FastScanner(System.in);
		int n= in.nextInt();
		int m= in.nextInt();
		
		if(Math.abs(n-m)>1){
			System.out.println(0);
			return;
		}
		if(n==m){
			BigInteger res= go(n);
			res= res.multiply(go(m));
			res= res.mod(new BigInteger(""+mod));
			res= res.multiply(new BigInteger("2"));
			res= res.mod(new BigInteger(""+mod));
			System.out.println(res.toString());
			return;
		}
		BigInteger res= go(n);
		res= res.multiply(go(m));
		res= res.mod(new BigInteger(""+mod));
		System.out.println(res.toString());
	}
	public static BigInteger go(int n){
		BigInteger res= BigInteger.ONE;
		for (int i = 1; i <=n; i++) {
			res= res.multiply(new BigInteger("" + i));
			res= res.mod(new BigInteger(""+mod));
		}
		return res;
	}
	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(InputStream in) {
			br = new BufferedReader(new InputStreamReader(in));
			st = new StringTokenizer("");
		}

		public double nextDouble() throws NumberFormatException, IOException {
			return Double.parseDouble(next());
		}

		public String next() throws IOException {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine());
				return next();
			}
			return st.nextToken();
		}

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

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