---
id: 113
lang: en
translation_of: index.md
source_sha256: 4dcbb54fcda054ac27b4919c2be98e95d7545f822358f074cee230d46d80d73f
title: "P1841: [JSOI2007] Important Cities — Solution"
description: "The idea is that while running floyed for shortest paths on the undirected graph, every new path found updates the important point."
tags: ["OI","Graph Theory","Floyed","P1841"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "floyed (the author's spelling of Floyd, also used in the code and the tag) kept as written."
  - "lornd is an online handle and kept as written. 给我写的 read as lornd giving the author this problem to solve."
---

## Approach

This problem was given to me to solve by lornd, <span class="slang" data-zh="巨佬" data-gloss="jùlǎo, “huge guy”. A very skilled contestant; used with admiration.">a big shot</span>. Since I'm too <span class="slang" data-zh="菜" data-gloss="cài, “vegetable”. Slang for being bad at something; weak.">weak</span>, I had no choice but to give up and read the solution. After reading the solution, I found the approach quite clever, so I'm here to share it.

The idea is that while running floyed for shortest paths on the undirected graph, every time a new path is found, the important point is updated once. The strategy is as follows:

1. If the original path is longer than the current path, update the path and record point k in cities[i][j].
2. If the original path equals the current path, the important point is not unique, so record cities[i][j] as -1.

Finally, search cities for the elements that are not -1, then sort and output them.

## Code

```cpp
// P1841.cpp
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
#define ll long long
ll mat[300][300];
int dp[300][300];
bool ans[500];
const ll INF = (ll)(0x7fffffff) / 3;
int n, m;

void floyed()
{
    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++)
            if (i != k)
                for (int j = 1; j <= n; j++)
                    if (i != j && j != k)
                        if (mat[i][k] + mat[k][j] < mat[i][j])
                            mat[i][j] = mat[i][k] + mat[k][j], dp[i][j] = k;
                        else if (mat[i][k] + mat[k][j] == mat[i][j])
                            dp[i][j] = -1;
}

void addpath(int src, int dst, ll w)
{
    mat[src][dst] = mat[dst][src] = w;
}

int main()
{
    fill(mat[0], mat[0] + 300 * 300, INF);
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        ll a, b, c;
        cin >> a >> b >> c;
        addpath(a, b, c);
    }
    floyed();
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (dp[i][j] != -1)
                ans[dp[i][j]] = true;
    bool flag = true;
    for (int i = 1; i <= n; i++)
        if (ans[i])
            cout << i << " ", flag = false;
    if (flag)
        cout << "No important cities.";
    return 0;
}
```
