#include using namespace std; typedef long long ll; // if you end up using long double, you need to set the floating point notation to fixed, and set the percision to be very high typedef long double ld; typedef pair pii; typedef pair pll; typedef vector vi; const ll INF = 2001001001; const ll INF2 = 2e18; const ll MOD = 1000000007; #define max3(a, b, c) max(a, max(b, c)) #define min3(a, b, c) min(a, min(b, c)) #define pb push_back #define pf push_front #define f first #define s second #define mp make_pair #define sz(x) (int)(x).size() #define all(x) begin(x), end(x) const bool testing = 0; mt19937 rng(63); // first four are north, west, east ,south int dir1[] = {1, 0, -1, 0, 1, 1, -1, -1}; int dir2[] = {0, 1, 0, -1, 1, -1, 1, -1}; int main() { // apparently this does fast i/o cin.tie(0) , ios::sync_with_stdio(0); cin.exceptions(cin.failbit); stringstream ss; int n, m, k; cin >> n >> m >> k; vector petals(n+1, 0); for(int i = 1; i <= n; i++){ int a; cin >> a; a--; petals[i] = a; } vector vec(n+1); vector indegs(n+1, 0); for(int i = 0; i < m; i++){ int a, b; cin >> a >> b; vec[a].pb(b); indegs[b]++; } ll sum = 0; queue q; for(int i = 1; i <= n; i++){ if(indegs[i] == 0) q.push(i); } vector ops; // for double checking vector petals_copy(petals); while(sz(q)){ int curr = q.front(); q.pop(); ll diff = k-1 - petals[curr]; petals[curr] = 0; for(auto a : vec[curr]){ petals[a] = (petals[a] + diff) % k; indegs[a]--; if(indegs[a] == 0){ q.push(a); } } sum += diff; ops.pb({curr, diff}); } cout << sum << "\n"; // double check for(auto p : ops){ petals_copy[p.f] += p.s; for(auto a : vec[p.f]){ petals_copy[a] += p.s; } } for(int i = 1; i <= n; i++){ assert(petals_copy[i] % k == k-1); } cout << ss.str(); return 0; }