Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 300300 points
Problem Statement
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?
Constraints
- 2≤N≤82≤N≤8
- If i≠ji≠j, 1≤Ti,j≤1081≤Ti,j≤108.
- Ti,i=0Ti,i=0
- Ti,j=Tj,iTi,j=Tj,i
- 1≤K≤1091≤K≤109
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
NN KK T1,1T1,1 …… T1,NT1,N ⋮⋮ TN,1TN,1 …… TN,NTN,N
Output
Print the answer as an integer.
Sample Input 1 Copy
Copy
4 330 0 1 10 100 1 0 20 200 10 20 0 300 100 200 300 0
Sample Output 1 Copy
Copy
2
There are six paths that start at City 11, visit all other cities exactly once, and then go back to City 11:
- 1→2→3→4→11→2→3→4→1
- 1→2→4→3→11→2→4→3→1
- 1→3→2→4→11→3→2→4→1
- 1→3→4→2→11→3→4→2→1
- 1→4→2→3→11→4→2→3→1
- 1→4→3→2→11→4→3→2→1
The times it takes to travel along these paths are 421421, 511511, 330330, 511511, 330330, and 421421, respectively, among which two are exactly 330330.
Sample Input 2 Copy
Copy
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 Copy
Copy
24
In whatever order we visit the cities, it will take the total time of 55 to travel.
思路:
暴搜,递归结束条件x == 1,cost == k
code:
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define N 100003
#define mod 100000
#define pb push_back
#define x first
#define y second
#define ull unsigned long long
#define ll long long
using namespace std;
vector<pair<int,int> >g[N];
int vis[N];
int n ,k ;
int cnt = 0;
void dfs(int x,int c)
{
if(x == 1 && c == k)
{
cnt ++;
return;
}
for(int i = 0;i < g[x].size();i++)
{
pair<int,int>p = g[x][i];
if(vis[p.x])
continue;
vis[p.x] = 1;
dfs(p.x,c+p.y);
vis[p.x] = 0;
}
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
cin >> n >> k;
int tmp;
memset(vis,0,sizeof(vis));
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
cin >> tmp;
g[i].push_back(make_pair(j,tmp));
}
}
dfs(1,0);
cout << cnt << endl;
return 0;
}