AtCoder题解 —— AtCoder Beginner Contest 183 —— C - Travel

题目相关

题目链接

AtCoder Beginner Contest 183 C 题,https://atcoder.jp/contests/abc183/tasks/abc183_c

Problem Statement

There are N cities. The time it takes to travel from City i to City j is Ti,j.

Among those paths that start at City 1, visit all other cities exactly once, and then go back to City 1, how many paths take the total time of exactly K to travel along?

Input

Input is given from Standard Input in the following format:

N K
T1,1 ... T1,N
.
.
TN,1 ... TN,N

Output

Print the answer as an integer.

Samples1

Sample Input 1

4 330
0 1 10 100
1 0 20 200
10 20 0 300
100 200 300 0

Sample Output 1

2

Explaination

There are six paths that start at City 1, visit all other cities exactly once, and then go back to City 1:

  • 1→2→3→4→1
  • 1→2→4→3→1
  • 1→3→2→4→1
  • 1→3→4→2→1
  • 1→4→2→3→1
  • 1→4→3→2→1

The times it takes to travel along these paths are 421, 511, 330, 511, 330, and 421, respectively, among which two are exactly 330.

Samples2

Sample Input 2

5 5
0 1 1 1 1
1 0 1 1 1
1 1 0 1 1
1 1 1 0 1
1 1 1 1 0

Sample Output 2

24

Explaination

In whatever order we visit the cities, it will take the total time of 5 to travel.

Constraints

  • 2≤N≤8
  • If i≠j, 1≤Ti,j≤10^8.
  • Ti,i=0
  • Ti,j=Tj,i
  • 1≤K≤10^9
  • All values in input are integers.

题解报告

题目翻译

有 N 个城市,从城市 i 到城市 j 需要的时间记为 Ti,j。问从城市 1 出发,经过所有的其他城市,再回到城市 1,而且每个城市只能走一次。求需要时间正好为 K 的线路个数。

样例数据分析

这个题目样例i数据解释中已经说明的非常详细,我们不需要分析样例数据。

题目分析

根据样例数据 1,一共有 4 个城市,我们知道从城市 1 出发遍历所有城市,这就是一个全排列问题。使用模拟算法,基本思路就是,写出所有从 1 出发的全排列,然后计算出这个路线需要的时间,如果和 K 相同,我们就找到了一个答案。

考虑到本题的数据 N 最大为 8。因此 8 个城市,从 1 出发的全排列为 7!=5040,也就是说模拟算法是可以在规定的时间内完成的。这样本问题就转换为如何写出全排列。

使用 C++ STL 写出全排列是一个非常容易的事情。我们可以使用 algrothim 库中的 next_permutation() 函数即可完成这个任务。

AC 参考代码

//https://atcoder.jp/contests/abc183/tasks/abc183_c
//C - Travel
#include <bits/stdc++.h>

using namespace std;

const int MAXN=10;
int nums[MAXN][MAXN];

int main() {
    int n,k;
    cin>>n>>k;

    int i;
    for (i=1; i<=n; i++) {
        for (int j=1; j<=n; j++) {
            cin>>nums[i][j];
        }
    }

    vector<int> idx(n+2);
    iota(idx.begin(), idx.end(), 0);
    idx[n+1]=1;
    int ans=0;
    do {
        int sum=0;
        for (i=2; i<=n+1; i++) {
            sum+=nums[idx[i-1]][idx[i]];
        }
        if (sum==k) {
            ans++;
        }
    } while (next_permutation(idx.begin()+2, idx.end()-1));

    cout<<ans<<"\n";

    return 0;
}

时间复杂度

O(N^2)。主要的时间消耗在读取数据上。

空间复杂度

O(N^2)。

问题扩展

当 N 持续扩大。比如 N 变成 11,这样 10!=3.7e6,继续使用模拟算法,就不一定能通过了。该如何改进算法?我去,我一下也没想明白。鸽一下。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力的老周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值