Official

A - 電力不足の都市 / City with Power Shortage Editorial by admin

DeepSeek V3

Overview

Given the power demand of each city and the capacity of transmission lines, this problem asks us to find the number of “power-deficient cities” where the supplied power falls below the demand.

Analysis

Reading the problem statement, the available power supply \(T_i\) for each city \(i\) is defined as the sum of the capacities of all transmission lines that have that city as an endpoint. In other words, by adding each transmission line’s capacity to both of its endpoint cities, we can calculate the total supply capacity for each city.

A straightforward approach is to add each transmission line’s capacity to both of its endpoint cities, and then compare \(T_i\) with \(S_i\) for each city at the end. This method runs efficiently within the problem’s constraints.

Algorithm

  1. Read the number of cities \(N\) and the number of transmission lines \(M\)
  2. Read the demand of each city \(S_1, S_2, \ldots, S_N\)
  3. Initialize an array \(T\) of size \(N+1\) to record the power supply of each city (initialized to 0)
  4. For each transmission line’s information:
    • Read the cities \(U_j\), \(V_j\) connected by the transmission line and its capacity \(W_j\)
    • Add \(W_j\) to \(T[U_j]\)
    • Add \(W_j\) to \(T[V_j]\)
  5. For all cities \(i\) (from 1 to \(N\)), check whether \(T[i] < S[i-1]\)
  6. Count and output the number of cities satisfying the condition

Complexity

  • Time complexity: \(O(N + M)\)
    • \(O(N + M)\) for reading input
    • \(O(M)\) for processing transmission lines
    • \(O(N)\) for checking cities
  • Space complexity: \(O(N)\)
    • \(O(N)\) for storing the demand list and supply array

Implementation Notes

  • Since city numbers start from 1, care must be taken with array indexing

  • To efficiently read the input data, all data is read and processed at once

  • To ensure correct behavior even when no transmission lines exist (\(M = 0\)), all \(T_i\) are set to 0 during initialization

    Source Code

import sys

def main():
    data = sys.stdin.read().split()
    if not data:
        print(0)
        return
        
    n = int(data[0])
    m = int(data[1])
    s_list = list(map(int, data[2:2+n]))
    
    t = [0] * (n + 1)
    
    index = 2 + n
    for _ in range(m):
        u = int(data[index])
        v = int(data[index+1])
        w = int(data[index+2])
        index += 3
        
        t[u] += w
        t[v] += w
        
    count = 0
    for i in range(1, n + 1):
        if t[i] < s_list[i - 1]:
            count += 1
            
    print(count)

if __name__ == "__main__":
    main()

This editorial was generated by deepseekv3.