codeforces 24A Ring road (dfs)

来源:互联网 发布:微信直播软件 编辑:程序博客网 时间:2024/05/29 15:30

题目链接:http://codeforces.com/problemset/problem/24/A


发现写dfs写得特别烂。

题目要求一个最小代价环。

题目数据意思是比如给了1,3,1那么表示路方向由1->3调整为3->1的代价是1,如果不去调整就不需要代价。

#include <bits/stdc++.h>using namespace std;const int maxn = 105;const int oo = 0xfffffff;int G[maxn][maxn];int vis[maxn];int n, x, y, l;int mincost = oo;// i:当前所在城市编号// cnt:已有城市数目// cost:已有代价void dfs(int pos, int cnt, int cost) {    if(cost >= mincost) {        return ;    }    if(cnt == n + 1) {        if(mincost > cost) {            mincost = cost;        }        return ;    }    int i = 2;    //从1出发,最后一次肯定回到1,i从1开始。    if(cnt == n) {        i = 1;    }    for (; i <= n; i ++) {        if(!vis[i] && G[pos][i] < oo) {            vis[i] = 1;            dfs(i, cnt + 1, cost);            vis[i] = 0;        }        if(!vis[i] && G[pos][i] == oo && G[i][pos] < oo) {            vis[i] = 1;            dfs(i, cnt + 1, cost + G[i][pos]);            vis[i] = 0;        }    }}int main() {    scanf("%d", &n);    for (int i = 1; i <= n; i ++) {        for (int j = 1; j <= i; j ++) {            G[i][j] = G[j][i] = oo;        }    }    for (int i = 0; i < n; i ++) {        scanf("%d%d%d", &x, &y, &l);        G[x][y] = l;    }    dfs(1, 1, 0);    printf("%d\n", mincost);    return 0;}


0 0
原创粉丝点击