There are NN cities. The time it takes to travel from City ii to City jj is Ti,jTi,j.
Among those paths that start at City 11, visit all other cities exactly once, and then go back to City 11, how many paths take the total time of exactly KK to travel along?
Input is given from Standard Input in the following format:
NN KK T1,1T1,1 …… T1,NT1,N ⋮⋮ TN,1TN,1 …… TN,NTN,N
Print the answer as an integer.
Inputcopy | Outputcopy |
---|---|
4 330 0 1 10 100 1 0 20 200 10 20 0 300 100 200 300 0 |
2 |
There are six paths that start at City 11, visit all other cities exactly once, and then go back to City 11:
The times it takes to travel along these paths are 421421, 511511, 330330, 511511, 330330, and 421421, respectively, among which two are exactly 330330.
Inputcopy | Outputcopy |
---|---|
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 |
24 |
In whatever order we visit the cities, it will take the total time of 55 to travel.
有 N 个城市,从城市 i 到城市 j 需要的时间记为 Ti,j。问从城市 1 出发,经过所有的其他城市,再回到城市 1,而且每个城市只能走一次。求需要时间正好为 K 的线路个数。
#include
#define int long long
#define ll long long
#define N 15
#define INF INT64_MAX
#define MINF 0x3f
#define eps 1e-9
using namespace std;
int n,x,m,k,t,ans=0,vis[N],c[N];
int a[N],b[N][N],t1[N],t2[N],sum=0,dp[101][505];
map mp; //map 数组作映射,记录前缀和相同的时候
void solve()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cin>>b[i][j];
}
vector idx(n+2); //初始化长度为n+2,因为0不用,n+1为最后回到1城市
iota(idx.begin(),idx.end(),0); //初始化索引为0
idx[n+1]=1; //初始化n+1为1城市
do{ //用do-while 是为了防止跳过第一次排列
sum=0;
for(int i=2;i<=n+1;i++)
{
sum+=b[idx[i-1]][idx[i]]; // sum只要加上每一次索引顺序后得到两个城市间距离
}
if(sum==m)
{
ans++;
}
}while(next_permutation(idx.begin()+2,idx.end()-1));//查询从第二个城市开始到第n个城市
cout<