Lightoj 1019 - Brush (V)

// Accepted
// Algorithm: Dijkstra

#include<bits/stdc++.h>

using namespace std;

#define fast ios_base::sync_with_stdio(0)
#define bfast cin.tie(0)
#define outs(x) cout << x << " "
#define outn(x) cout << x << "\n"
#define sf scanf
#define pf printf
#define nl puts("")
#define psb push_back
#define mset(c,v) memset(c , v , sizeof c)
#define loop0(n) for(int i=0; i<n; i++)
#define loop1(n) for(int i=1; i<=n; i++)
#define mpair(x , y) make_pair(x , y)
#define all(x) x.begin(), x.end()
#define pi acos(-1.0)
#define psb push_back

typedef unsigned long long ull;
typedef long long LL;
typedef vector<int>vii;
typedef vector<LL>vll;
typedef vector<string>vs;
typedef map<int, int>mpii;
typedef map<string, int>mpsi;
typedef map<char, int>mpci;
typedef map<LL, LL>mpll;

const int mod = 1000007;
const int high = 102;
const int inf = 1e6+8;

int dis[high], visited[high];

struct data
{
    int node , cost;

    data() { }

    data(int u , int c)
    {
        node = u;
        cost = c;
    }

    bool operator < (const data & b) const
    {
        return cost > b.cost;
    }
};


vector<data>adj[high];

void clrAll()
{
    for(int i=0; i<high; i++)
    {
        adj[i].clear();
        visited[i] = 0;
        dis[i] = inf;
    }
}

void Dijkstra(int s)
{
    dis[s] = 0;

    priority_queue<data>Q;

    Q.push(data(s, 0));

    while(!Q.empty())
    {
        int u = Q.top().node;
        int w = Q.top().cost;

        Q.pop();

        if(visited[u]) continue;

        visited[u] = 1;

        for(int i=0; i<adj[u].size(); i++)
        {
            int v = adj[u][i].node;
            int cost = adj[u][i].cost + w;

            if(dis[v] > cost)
            {
                dis[v] = cost;

                Q.push(data(v , cost));
            }
        }
    }
}

int main()
{
    int i , u , v , N , M, w , test , tc=0;
    sf("%d", &test);
    while(test--)
    {
        clrAll();

        sf("%d %d", &N , &M);

        for(i=0; i<M; i++)
        {
            sf("%d %d %d", &u , &v , &w);

            adj[u].psb(data(v , w));
            adj[v].psb(data(u , w));
        }

        Dijkstra(1);

        pf("Case %d: " , ++tc);

        if(dis[N] == inf) pf("Impossible\n");
        else pf("%d\n" , dis[N]);
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number