ALCATRAZ2 - GO GOA GONE | SPOJ



So, it was winter and Me and 8 of my friends decided to plan a trip to GOA. Since the Bars and Clubs are too Expensive out there, we decided to pool money together for our whole trip expenses. Now since every group has some internal politics going on, the same applies to our group also :P . 2 Members that are having a cold war between them won't go to the trip if the other one is going. But Since we want to enjoy a lavish party, we want to maximize the pooled money. So, for this task, I've chosen my Marwari friend Mohit to solve this problem  ( He's good at money matters ). Your task is to help Mohit achieve the maximum pooled money.

Input

First Line will contain  8 space-separated integers denoting the money contributed by each member in order.
The next line will contain the total number of pairs having a cold war between them. Let us denote this by P.
The next P lines will contain 2 numbers separated by a space showing the members having a cold war. Numbers used to denote members will be ( 1-8 ) for each 8 members.
Constraints:
Everything is guarenteed to  easily fit in 32 bit integer type  . 
Output description
Output will give the maximum amt of money that can be pooled.
Example
Input: 
3 14 5 2 3 4 1 9 
4
1 2
2 3
4 5
7 8
Output:
30


Solution (C++) :

#include <iostream>

#include <vector>

using namespace std;


int m;

int a[8];

int assignment[8];

int finalAns = 0;

vector <int> Adjlist[8];


void backtrack(int n) {

    for (int i = 0; i < 2; i++) {

        assignment[n] = i;

        if (n == 7) {

            bool satisfied = true;

            for (int j = 0; j < 8; j++)

                if (assignment[j] == 1) {

                    for (int zz = 0; zz < Adjlist[j].size(); zz++)

                        if (assignment[Adjlist[j][zz]] == 1)

                            satisfied = false;

                }

            if (satisfied) {

                int tmp = 0;

                for (int j = 0; j < 8; j++)

                    if (assignment[j] == 1) {

                        tmp += a[j];

                    }

                if (tmp > finalAns)

                    finalAns = tmp;

            }

        } else

            backtrack(n+1);

        assignment[n] = 0;

    }

}


int main() {

    int tmpA, tmpB;

    for (int i = 0; i < 8; i++) {

        cin >> a[i];

        assignment[i] = 0;

    }

    cin >> m;

    for (int i = 0; i < m; i++) {

        cin >> tmpA >> tmpB;

        Adjlist[tmpA-1].push_back(tmpB-1);

        Adjlist[tmpB-1].push_back(tmpA-1);

    }

    backtrack(0);

    cout << finalAns << "\n";

} 


Comments

Popular posts from this blog

Boxes through a Tunnel | HackerRank

Array Manipulation | HackerRank

String Validators | HackerRank