只要保证每次都是加一个新的点进集合,不就可以代替并查集了吗,求大佬解释。
未过代码如下:
#include <iostream>
using namespace std;
inline char getch()
{
static char buf[1000005], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1000005, stdin), p1 == p2) ? EOF : *p1 ++ ;
}
template<typename Type>
inline void read(Type &x)
{
char c; bool t;
x = t = 0, c = getch();
while (c < '0' || c > '9') t |= (c == '-'), c = getch();
while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getch();
x = t ? -x : x;
}
const int N = 10, M = 60;
int n, m, to[M], head[N], ne[M], idx = 1;
long long k, we[M], ans = LLONG_MAX;
bool st[N];
void add(int u, int v, long long w)
{
to[idx] = v;
we[idx] = w;
ne[idx] = head[u];
head[u] = idx ++ ;
}
void dfs(int u, int cnt, long long cost)
{
if (cost >= ans) return;
if (cnt == n - 1) {ans = min(ans, cost); return;}
for (int i = head[u]; i ; i = ne[i])
{
if (!st[to[i]])
{
st[to[i]] = 1;
dfs(to[i], cnt + 1, (cost + we[i]) % k);
st[to[i]] = 0;
}
}
}
int main()
{
freopen("@Public Example.txt", "r", stdin);
read(n), read(m), read(k);
for (int i = 1; i <= m; i ++ )
{
long long w; int u, v;
read(u), read(v), read(w);
add(u, v, w);
add(v, u, w);
}
for (int i = 1; i <= n; i ++ ) st[i] = 1, dfs(i, 0, 0), st[i] = 0;
printf("%lld\n", ans);
return 0;
}