Thursday, July 19, 2018

UVA 10305-Ordering Tasks

John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.

Input

The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 <= n <= 100 and m. n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j, representing the fact that task i must be executed before task j. An instance with n = m = 0 will finish the input.
Output
For each instance, print a line with n integers representing the tasks in a possible order of execution.

Output

For each instance, print a line with n integers representing the tasks in a possible order of execution.

Sample Input

5 4
1 2
2 3
1 3
1 5
0 0

Sample Output

1 4 2 5 3

Analysis

In this problem we are said to order some tasks. As every task is not independent, so we can use Toplogical Sort algorithm here to solve. 

 

Solution

#include<bits/stdc++.h>
using namespace std;

vector <int> G[105];
vector <int> processed;
queue <int> q;
int n, m;
int indegree[105];

void topsort()
{
    int u;
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        processed.push_back(u);
        for(int i=0; i<G[u].size(); i++)
        {
            int v=G[u][i];
            indegree[v]--;
            if(indegree[v]==0)
            {
                q.push(v);
            }
        }
    }
}

int main()
{
    int u, v;
    while(scanf("%d%d", &n, &m)==2)
    {
        if(n==0 && m==0)
            break;
        memset(indegree, 0, sizeof(indegree));
        for(int i=0; i<m; i++)
        {
            scanf("%d%d", &u, &v);
            indegree[v]++;
            G[u].push_back(v);
        }
        for(int i=1; i<=n; i++)
        {
            if(indegree[i]==0)
            {
                q.push(i);
            }
        }
        topsort();
        for(int i=0; i<processed.size(); i++)
        {
            if(i== (processed.size()-1))
            {
                printf("%d", processed[i]);
            }
            else
            {
                printf("%d ", processed[i]);
            }
        }
        processed.clear();
        for(int i=1; i<=n; i++)
        {
            G[i].clear();
        }
        printf("\n");
    }
    return 0;
}

Topological Sort

কম্পিউটার বিজ্ঞানে টাস্ক অর্ডারিং করার জন্য টপোলজিক্যাল শর্ট অনেক জনপ্রিয়। কম্পিউটারকে যখন অনেক টাস্ক হ্যান্ডেল করতে হয়, তখন এই এলগোরিদমটি অনেক সাহায্য করে। আমাদের দৈনন্দিন জীবনেও বিভিন্ন টাস্ক অর্ডারিং করতে টপোলজিক্যাল শর্টের অনেক গুরুত্ব রয়েছে। কম্পিউটার বিজ্ঞানে তোমাকে অনেকগুলো কোর্স পড়তে হয়। তোমাকে সি, সি++, ফিজিক্স, কেমিস্ট্রি, ডাটা স্ট্রাকচার, এলগোরিদম ইত্যাদি কোর্স পড়তে হয়। এইসব সাবজেক্ট কি তোমার ইচ্ছা মতো  অর্ডারিং এ পড়তে পারো ??? যেমন আগে এলগোরিদম এরপর সি। উত্তরটি হবে না!!! সাবজেক্টগুলো একটি নির্দিষ্ট অর্ডার ফলো করে তোমাকে পড়তে হয়। কোন কোর্সের পর কোন কোর্স পড়তে হবে নিচে তার একটি তালিকা দেয়া হল।
ফিজিক্স ->সি; কেমিস্ট্রি ->সি; সি ->সি ++; সি -> এলগোরিদম; সি -> ডাটা স্ট্রাকচার; সি++ -> ডাটা স্ট্রাকচার; সি++ -> এলগোরিদম; ডাটা স্ট্রাকচার-> এলগোরিদম; 
এখন প্রতিটি কোর্সকে একটি নোড হিসেবে কল্পনা করে একটি ডিরেক্টেড গ্রাফ আঁকি।
প্রতিটি কোর্স বা নোডের পাশে সংখ্যা দ্বারা ইনডিগ্রী বোঝানো হয়েছে। কোন নোডে যতটি এজ প্রবেশ করে তার সংখ্যা হিসেবে করে ইনডিগ্রী নির্ণয় করা হয়। টপোলজিক্যাল শর্ট এ যে নোডের ইনডিগ্রী জিরো সেই নোড নিয়ে অর্ডারিং শুরু করতে হয়। এখানে ফিজিক্স ও কেমিস্ট্রি দুটি নোডেরই ইনডিগ্রী শূন্য। তাই যেকোন একটি নিয়ে শুরু করতে পারি। যে নোড নিয়ে কাজ করব সেই নোড থেকে যেসব এজ বের হয়েছে সেই গুলো ডিলিট করব।

এখন মনেকর, আমরা আগে ফিজিক্স পড়ব। তাই ফিজিক্স থেকে সি এর এজটি ডিলিট করে দেই এবং সি এর ইনডিগ্রি এক কমবে।
এবার যেহেতু কেমিস্ট্রি এর ইনডিগ্রী শূন্য তাই কেমিস্ট্রি পড়ব। কেমিস্ট্রি থেকে সি এর এজটি ডিলিট করে দেই এবং সি এর ইনডিগ্রী এক কমিয়ে দেই।


এবার যেহেতু সি এর ইনডিগ্রী শূন্য তাই সি পড়ব। সি থেকে যেসব এজ বের হয়েছে সবগুলো ডিলিট করে দেই।

এবার যেহেতু সি++ এর ইনডিগ্রী শূন্য তাই সি++ পড়ব। সি++ থেকে যেসব এজ বের হয়েছে সবগুলো ডিলিট করে দেই।
এবার যেহেতু ডাটা স্ট্রাকচার এর ইনডিগ্রী শূন্য তাই ডাটা স্ট্রাকচার পড়ব। ডাটা স্ট্রাকচার থেকে যেসব এজ বের হয়েছে সবগুলো ডিলিট করে দেই।
এখন যেহেতু এলগোরিদম এর ইনডিগ্রী শূন্য তাই এলগোরিদম পড়ব। এভাবে তুমি কোর্স গুলো পড়ার অর্ডারিং পেয়ে গেছো। অর্ডারিংটি এমন- ফিজিক্স->কেমিস্ট্রি->সি->সি++ -> ডাটা স্ট্রাকচার-> এলগোরিদম। এভাবেই টপোলজিক্যাল শর্ট কাজ করে। এবার টপোলজিক্যাল শর্ট এর এলগোরিদমটি দেখ নিচে-
  1. প্রথমে প্রতিটি নোডের ইনডিগ্রী নির্ণয় করতে হবে
  2. যেসব নোডের ইনডিগ্রি শূন্য সেই নোড গুলোকে একটি কিউতে রাখি।
  3. যতক্ষণ পর্যন্ত কিউ খালি না হয়, 4 ও 5 নম্বর ষ্টেপের জন্য লুপ চালাই
  4.          কিউ থেকে ফ্রন্টের নোড N রিমুভ করি
  5.          নোড N এর সাথে যুক্ত প্রতিটি নোড M এর জন্য নিচের দুটি স্টেপ রিপিট করি        
  • নোড N ও নোড M এর এজ ডিলিট করি
  • যেসব নোডের ইনডিগ্রী শূন্য হবে সেই গুলো কিউতে রাখি
আমরা টপোলজিক্যাল শর্ট বোঝার জন্য একটি উদাহরণ ও এলগোরিদম দেখলাম। এখন এলগোরিদমটির ইমপ্লিমেন্টেশন দেখব।

Code: 

/*  Topological Sort-Indegree  */

#include<bits/stdc++.h>
using namespace std;

vector <int> G[105];
vector <int> processed;
queue <int> q;
int indegree[105];
int n, m;

void topsort()
{
    int u;
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        processed.push_back(u);
        for(int i=0; i<G[u].size(); i++)
        {
            int v=G[u][i];
            indegree[v]--;
            if(indegree[v]==0)
            {
                q.push(v);
            }
        }
    }
}

int main()
{
    int u, v;
    while(scanf("%d%d", &n, &m)==2)
    {
        if(n==0 && m==0)
            break;
        memset(indegree, 0, sizeof(indegree)); // Initialize indegree of all node to zero
        for(int i=0; i<m; i++)
        {
            scanf("%d%d", &u, &v);
            indegree[v]++;  // Increment indegree of nodes
            G[u].push_back(v);
        }

        /* Finding nodes having zero indegree and push them into queue */
        for(int i=1; i<=n; i++)
        {
            if(indegree[i]==0)
            {
                q.push(i);
            }
        }

        topsort();

        for(int i=0; i<processed.size(); i++)
        {
            printf("%d ", processed[i]);
        }
        processed.clear();
        for(int i=1; i<=n; i++)
        {
            G[i].clear();
        }
        printf("\n");
    }
    return 0;
}
টপোলজিক্যাল শর্ট রিলেটেড প্রোগ্রামিং প্রবলেমের লিংক- UVA 10305-Ordering Tasks

Tuesday, July 10, 2018

UVA 11631-Dark Roads

Economic times these days are tough, even in Byteland. To reduce the operating costs, the government of Byteland has decided to optimize the road lighting. Till now every road was illuminated all night long, which costs 1 Bytelandian Dollar per meter and day. To save money, they decided to no longer illuminate every road, but to switch off the road lighting of some streets. To make sure that the inhabitants of Byteland still feel safe, they want to optimize the lighting in such a way, that after darkening some streets at night, there will still be at least one illuminated path from every junction in Byteland to every other junction.
What is the maximum daily amount of money the government of Byteland can save, without making
their inhabitants feel unsafe?

 

Input

The input le contains several test cases. Each test case starts with two numbers m and n, the number of junctions in Byteland and the number of roads in Byteland, respectively. Input is terminated by m = n = 0. Otherwise, 1 <=m <= 200000 and m-1 <=n <=200000. Then follow n integer triples x, y, z specifying that there will be a bidirectional road between x and y with length z meters (0 <=x; y < m and x ̸= y). The graph speci ed by each test case is connected. The total length of all roads in each test case is less than 2^31.

 

Output

For each test case print one line containing the maximum daily amount the government can save.

 

Sample Input

7 11
0 1 7
0 3 5
1 2 8
1 3 9
1 4 7
2 4 5
3 4 15
3 5 6
4 5 8
4 6 9
5 6 11
0 0

Sample Output

51

 

Analysis

This Problem can be solved by using Minimum Spanning Tree (MST). We have learned about Kruskal algorithm. Here in the problem we are told to find out maximum amount of saving of government for lighting the street. Firstly we will calculate total cost for lighting the streets. Then we will apply Kruskal algorithm. After that from total cost we will deduct the amount found by kruskal algorithm. By this we can easily find maximum amount of  saving.

Solution  


#include <bits/stdc++.h>
using namespace std;

struct edge
{
    long long int u;
    long long int v;
    long long int w;
};

bool cmp(edge a, edge b)
{
    return a.w<b.w;
}

long long int pr[200100], n, m, mst, s[200100];
edge e[200100];

long long int find_set(long long int r)
{
    if(pr[r]==r)
        return r;
    else
        find_set(pr[r]);
}

long long int kruskal()
{
    sort(e,e+m,cmp);
    long long int cnt=0;

    for(long long int i=0; i<m && cnt<n-1; i++)
    {
        long long int u=find_set(e[i].u);
        long long int v=find_set(e[i].v);

        if(u!=v)
        {
            if(s[u]>s[v])
                swap(u, v);
            s[v]+=s[u];
            mst+=e[i].w;
            pr[u]=v;
            cnt++;
        }
    }
}

int main()
{
    long long int u,v,w;
    while(scanf("%lld%lld", &n, &m)==2)
    {
        if(n==0 && m==0)
            break;
        mst=0;
        long long int total=0;
        for(long long int i=0; i<m; i++)
        {
            pr[i]=i;
            s[i]=1;
            scanf("%lld%lld%lld", &u, &v, &w);
            total+=w;
            edge get;
            get.u=u;
            get.v=v;
            get.w=w;
            e[i]=get;
        }
        s[m]=1;
        pr[m]=m;
        kruskal();
        printf("%lld\n", total-mst);
    }
    return 0;
}

Kruskal Algorithm

ক্রুসকাল এলগোরিদম  দিয়ে আমরা সহজেই মিনিমাম স্প্যানিং ট্রি বের করতে পারি। ক্রুসকাল সম্পর্কে বিস্তারিত বলার আগে কিছু ডেফিনেশন জানিয়ে দেই।
একটি গ্রাফ থেকে কিছু নোড ও এজ নিয়ে আমরা সাব গ্রাফ তৈরি করতে পারি। স্প্যানিং ট্রি ও এক ধরণের সাব গ্রাফ যাতে মূল গ্রাফের সব নোড গুলো আছে কিন্তু এজ থাকবে n-1 টি যেখানে n হচ্ছে নোড সংখ্যা। একটি গ্রাফ থেকে অনেক গুলো স্প্যানিং ট্রি তৈরী করা যায়, যে স্প্যানিং ট্রি এর এজের ওয়েইটের যোগফল সর্বনিম্ন হবে তাকে  মিনিমাম স্প্যানিং ট্রি বলে। ট্রি তে সাইকেল থাকতে পারে না। 
যখন কোন গ্রাফে কোন নোড থেকে ট্রাভার্স শুরু করে বিভিন্ন এজ ট্রাভার্স করে আবার সেই নোডে ফিরে আসা যায় তাকে সাইকেল বলে।

উপরের গ্রাফটি দিয়ে ক্রুসকাল এলগোরিদম বুঝতে চেষ্টা কর। উপরের গ্রাফের এজগুলোকে প্রথমে ওয়েইট এর উপর ভিত্তি করে ছোট থেকে বড় এই অর্ডারে সাজাই। এরপর নিচের স্টেপগুলো এক্সেকিউট করব-
  1. দুটি নোডের মধ্যে যে এজের ওয়েইট কম সেটি আগে নিব অর্থাৎ ওই দুটি নোড ওই এজ দ্বারা কানেক্ট করব।
  2. দুটি নোডের মধ্যে যে এজের ওয়েইট বেশি সেটি পরে নিব অর্থাৎ ওই দুটি নোড ওই এজ দ্বারা কানেক্ট করব না 
  3. দুটি এজের ওয়েইট সমান হলে যে কোন একটি নিব
  4. এভাবে নোড গুলো কানেক্ট করার সময় যাতে সাইকেল তৈরী না হয় সেটি খেয়াল রাখতে হবে।
এখন AD ও CE দুটি এজেরই ওয়েইট সর্বনিম্ন। যেকোন একটি নেয়া যাবে। আমরা AD নিব।
 এরপর CE কে নেই
এরপর DF কে নেই
এরপর AB কে নেই
এরপর BE কে নেই
এখন BC ও EF কে নিব না কারন গ্রাফে সাইকেল তৈরি হবে। এরপর EG কে নেই
এখন BD, FG ও DE কে নিব না কারন গ্রাফে সাইকেল তৈরি হবে। এই অবস্থায় আমরা যে স্প্যানিং ট্রি টি পেলাম এটিই মিনিমাম স্প্যানিং ট্রি (MST)। 
ক্রুসকাল এলগোরিদম এর কনসেপ্ট আশা করি বুঝতে পেরেছ। আমরা যখন কোন এজ নেয়, এবং দুটি নোডের মধ্যে কানেক্ট করি, তখন ওই দুই নোডের মধ্যে পথ আছে কিনা তা জানা জরুরি। এটি আমরা ডিসজয়েন্ট সেট এলগোরিদম থেকে জানতে পারি। আমরা ক্রুসকাল এলগোরিদম এর ইম্প্লিমেন্টেশনে ডিসজয়েন্ট সেট এর কনসেপ্ট ব্যবহার করব। তাই ডিসজয়েন্ট সেট নিয়ে ইউটিউবের টিউটোরিয়ালটি আগে দেখে এসো-

Code:

/*  Kruskal */

#include <bits/stdc++.h>
using namespace std;

struct edge
{
    int u;
    int v;
    int w;
};

bool cmp(edge a, edge b)
{
    return a.w<b.w;
}

int pr[100],n,m;
edge c[100];

int find_set(int r) //parent find
{
    if(pr[r]==r)
        return r;
    else
        find_set(pr[r]);
}

int kruskal()
{
    sort(c,c+m,cmp); //sorting edges according to cost

    for(int i=1; i<=n; i++)
    {
        pr[i]=i;
    }

    int cnt=0,mst=0;

    for(int i=0; i<m && cnt<n-1; i++)
    {
        int u=find_set(c[i].u);
        int v=find_set(c[i].v);

        if(u!=v)
        {
            printf("%d %d %d\n",c[i].u, c[i].v, c[i].w);
            mst+=c[i].w;
            pr[u]=v;
            cnt++;
        }
    }
    return mst;
}

int main()
{
    scanf("%d%d", &n, &m);// n is number of nodes, m is number of edges

    for(int i=0; i<m; i++)
    {
        int u,v,w;
        scanf("%d%d%d", &u, &v, &w);
        edge input;
        input.u=u;
        input.v=v;
        input.w=w;
        c[i]=input;
    }

    printf("Minimum Spanning tree :\n");
    printf("%d", kruskal());
    return 0;
}

/*
Input:
7 11
1 2 7
1 4 5
2 3 8
2 4 9
2 5 7
3 5 5
4 5 15
4 6 6
5 6 8
5 7 9
6 7 11
*/

ক্রুসকাল এলগোরিদম রিলেটেড প্রোগ্রামিং প্রবলেম Link- UVA 11631-Dark Roads

Saturday, July 7, 2018

UVA 352-Seasonal War

The inhabitants of Tigerville and Elephantville are engaged in a seasonal war. Last month, Elephantvillesuccessfully launched and orbited a spy telescope called the Bumble Scope. The purpose of the BumbleScope was to count the number of War Eagles in Tigerville. The Bumble Scope, however, developed two problems because of poor quality control during its construction. Its primary lens was contaminated with bugs which block part of each image, and its focusing mechanism malfunctioned so that imagesvary in size and sharpness.

The computer programmers, who must rectify the Bumble Scope’s problems are being held hostage in a Programming Contest Hotel in Alaland by elephants dressed like tigers. The Bumble Scope’s flawed images are stored by pixel in a file called Bumble.in. Each image is square and each pixel or cell contains either a 0 or a 1. The unique Bumble Scope Camera (BSC) records at each pixel location
a 1 if part or all of a war eagle is present and a 0 if any other object, including a bug, is visible. 
The programmers must assume the following:
a) A war eagle is represented by at least a single binary one.
b) Cells with adjacent sides on common vertices, which contain binary ones, comprise one war eagle.
A very large image of one war eagle might contain all ones.
c) Distinct war eagles do not touch one another. This assumption is probably flawed, but the
programmers are desperate.
d) There is no wrap-around. Pixels on the bottom are not adjacent to the top and the left is not
adjacent to the right (unless, of course, there are only 2 rows or 2 columns)

Input and Output

Write a program that reads images of pixels from the input file (a text file), correctly counts the number
of war eagles in the images and prints the image number and war eagle count for that image on a single
line in the output file (also a text file).
Use the format in the sample output. Do this for each image in the input file. Each image will be
preceded by a number indicating its square dimension. No dimension will exceed 25.

Sample input

6
100100
001010
000000
110000
111000
010100
8
01100101
01000001
00011000
00000010
11000011
10100010
10000001
01100000

Sample output

Image number 1 contains 3 war eagles.
Image number 2 contains 6 war eagles.

Analysis

In the problem we have to find out number of war eagle. We can start counting war eagle where there is 1. From any cell we can move to any direction that means at 8 direction. By using DFS algorithm, we can easily count war eagle.

 

Solution 

#include <bits/stdc++.h>
using namespace std;
int xx[]= {0,0,1,1,-1,-1,1,-1}; //For 8 direction
int yy[]= {1,-1,1,-1,1,-1,0,0}; // For 8 direction

char s[105][105];
bool visit[105][105];
int ans;

int sx,sy,r;

void dfs(int ux,int uy)
{
    for(int i=0; i<8; i++)
    {
        int vx=ux+xx[i];
        int vy=uy+yy[i];

        if(vx<0 || vy<0 || vx>=r || vy>=r) continue;

        if(visit[vx][vy]==1 || s[vx][vy]=='0') continue;

        if(visit[vx][vy]==0)
        {
            visit[vx][vy]=1;

            dfs(vx,vy);
        }
    }
}


int main()
{
    int kase=0;
    while(scanf("%d", &r)==1)
    {
        ans=0;
        memset(visit,0,sizeof(visit));
        for(int i=0; i<r; i++)
        {
            scanf("%s",s[i]);
        }
        for(int i=0; i<r; i++)
        {
            for(int j=0; j<r; j++)
            {
                if(visit[i][j]==0 && s[i][j]=='1')
                {
                    visit[i][j]=1;
                    ans++;
                    dfs(i, j);
                }
            }
        }
        printf("Image number %d contains %d war eagles.\n",++kase, ans);
    }
    return 0;
}

LightOJ 1337-The Crystal Maze

You are in a plane and you are about to be dropped with a parasuit in a crystal maze. As the name suggests, the maze is full of crystals. Your task is to collect as many crystals as possible.
To be more exact, the maze can be modeled as an M x N 2D grid where M denotes the number of rows and N denotes the number of columns. There are three types of cells in the grid:
  1. A '#' denotes a wall, you may not pass through it.
  2. A 'C' denotes a crystal. You may move through the cell.
  3.  A '.' denotes an empty cell. You may move through the cell.
     Now you are given the map of the maze, you want to find where to land such that you can collect maximum number of crystals. So, you are spotting some position x, y and you want to find the maximum number of crystals you may get if you land to cell (x, y). And you can only move vertically or horizontally, but you cannot pass through walls, or you cannot get outside the maze.

 

Input

Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with a line containing three integers M, N and Q (2 ≤ M, N ≤ 500, 1 ≤ Q ≤ 1000). Each of the next M lines contains N characters denoting the maze. You can assume that the maze follows the above restrictions.
Each of the next Q lines contains two integers xi and yi (1 ≤ xi ≤ M, 1 ≤ yi ≤ N) denoting the cell where you want to land. You can assume that cell (xi, yi) is empty i.e. the cell contains '.'.

 

Output

For each case, print the case number in a single line. Then print Q lines, where each line should contain the maximum number of crystals you may collect if you land on cell (xi, yi).

Sample Input

Output for Sample Input

1
4 5 2
..#..
.C#C.
##..#
..C#C
1 1
4 1
Case 1:
1
2

Analysis

We have to collect maximum number of crystal maze. By using DFS algorithm, we can count the number of crystal maze. From DFS algorithm we have known how to traverse reachable nodes from any node.

Solution

#include<bits/stdc++.h>
using namespace std;
int xx[]= {1,-1,0,0};
int yy[]= {0,0,1,-1};
char s[505][505];
int visit[505][505];
int r, c, p, qo;
int ans[1005];

int dfs(int ux, int uy)
{
    if(s[ux][uy]=='C')
    {
        qo++;
    }
    for(int i=0; i<4; i++)
    {
        int vx=ux+xx[i];
        int vy=uy+yy[i];

        if(vx<0 || vy<0 || vx>=r || vy>=c)
            continue;

        if(visit[vx][vy]!=0 || s[vx][vy]=='#')
            continue;

        visit[vx][vy]=p;
        dfs(vx,vy);
    }
}

int main()
{
    int t_case, t=0, a, b, q;
    scanf("%d", &t_case);
    while(t_case--)
    {
        memset(visit, 0, sizeof(visit));
        memset(ans, 0, sizeof(ans));
        p=1;
        scanf("%d%d%d", &r, &c, &q);
        for(int i=0; i<r; i++)
        {
            scanf("%s", s[i]);
        }
        printf("Case %d:\n", ++t);
        for(int j=0; j<q; j++)
        {
            scanf("%d%d", &a, &b);
            a=a-1;
            b=b-1;
            if(visit[a][b]==0)
            {
                qo=0;
                visit[a][b]=p;
                dfs(a, b);
                ans[p]=qo;
                p++;
            }
            printf("%d\n", ans[visit[a][b]]);
        }
    }
    return 0;
}

LightOJ 1012-Guilty Prince

Once there was a king named Akbar. He had a son named Shahjahan. For an unforgivable reason the king wanted him to leave the kingdom. Since he loved his son he decided his son would be banished in a new place. The prince became sad, but he followed his father's will. In the way he found that the place was a combination of land and water. Since he didn't know how to swim, he was only able to move on the land. He didn't know how many places might be his destination. So, he asked your help.
For simplicity, you can consider the place as a rectangular grid consisting of some cells. A cell can be a land or can contain water. Each time the prince can move to a new cell from his current position if they share a side.

Now write a program to find the number of cells (unit land) he could reach including the cell he was living.

 

Input

Input starts with an integer T (≤ 500), denoting the number of test cases.
Each case starts with a line containing two positive integers W and H; W and H are the numbers of cells in the x and y directions, respectively. W and H are not more than 20.
There will be H more lines in the data set, each of which includes W characters. Each character represents the status of a cell as follows.
1) '.' - land
2) '#' - water
3) '@' - initial position of prince (appears exactly once in a dataset)

 

Output

For each case, print the case number and the number of cells he can reach from the initial position (including it).

Sample Input

Output for Sample Input

4
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
Case 1: 45
Case 2: 59
Case 3: 6
Case 4: 13

Analysis  

As we have to find out number of land from certain position, we can apply DFS algorithm here. According to DFS algorithm we can traverse all the reachable nodes from a given node.

 

Solution 

#include <bits/stdc++.h>
using namespace std;
int xx[]= {1,-1,0,0};
int yy[]= {0,0,1,-1};

char s[105][105];
bool visit[105][105];
int ans;

int sx,sy,r,c;

void dfs(int ux,int uy)
{
    ans++;
    for(int i=0; i<4; i++)
    {
        int vx=ux+xx[i];
        int vy=uy+yy[i];

        if(vx<0 || vy<0 || vx>=r || vy>=c) continue;

        if(visit[vx][vy]==1 || s[vx][vy]=='#') continue;

        if(visit[vx][vy]==0)
        {
            visit[vx][vy]=1;
            dfs(vx,vy);
        }
    }
}


int main()
{
    int i,j,k,tc,t=1;
    scanf("%d", &tc);
    while(tc--)
    {
        scanf("%d%d", &c, &r);
        memset(visit,0,sizeof(visit));
        for(i=0; i<r; i++)
        {
            scanf("%s",s[i]);
            for(j=0; j<c; j++)
            {
                if(s[i][j]=='@')
                {
                    sx=i;
                    sy=j;
                }
            }
        }
        visit[sx][sy]=1;
        ans=0;
        dfs(sx,sy);
        printf("Case %d: %d\n",t++,ans);
    }
    return 0;
}

UVA 469-Wetlands of Florida

A construction company owns a large piece of real estate within the state of Florida. Recently, the company decided to develop this property. Upon inspection of the property, however, it was revealed that the land, at various locations, contained bodies of water. This came as a shock to the owners of the company, for they were from out of state and not familiar with wetlands of Florida. The situation was very grave and the owners not knowing that such bodies of water can be converted to beautiful lakes that will increase the value of the land around them, were about to abandon the construction project. Fortunately, this fact was brought to the owners' attention by a smart FIU graduate who worked for the company and consequently the construction project started.

The engineers divided the construction site by a grid into uniform square cells such that each square cell entirely contained either water or land. (How they did it, of course, is anybody's guess.) Now, the question that the engineers are to answer is the following: ``Given the row and column number of a grid cell that contains water, what is the area of the lake containing that cell.'' (an area is measured by number of grid cells it contains. Diagonal cells are considered to be adjacent.)
You are to write a program to answer this question!

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

Each input set consists of 0<n<=99 lines each containing 0<m<=99 character long sequence of ``L''s and ``W''s followed by k > 0 lines each containing a pair of integers i and j. The first n lines will represent the n X m grid covering the land where a ``W''/``L'' at the c th character of the r th line indicates water/land within the cell at row r and column c of the grid. The pairs of integers on the last k lines, each represent the row and column numbers of some grid cell that contains water.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
The output for each pair of integers, i and j, on the last k lines of input, consists of an integer, on a separate line, indicating the area of the lake containing the grid cell, at row i and column j of the grid.

 

Sample Input

1
LLLLLLLLL
LLWWLLWLL
LWWLLLLLL
LWWWLWWLL
LLLWWWLLL
LLLLLLLLL
LLLWWLLWL
LLWLWLLLL
LLLLLLLLL
3 2
7 5

Sample Output

12
4


Analysis  

As we have to find out number of wet land from certain position, we can apply DFS algorithm here. According to DFS algorithm we can traverse all the reachable nodes from a given node.  

Solution

#include <bits/stdc++.h>
using namespace std;
int xx[]= {0,0,1,1,-1,-1,1,-1}; //For 8 direction
int yy[]= {1,-1,1,-1,1,-1,0,0}; // For 8 direction

char s[105][105];
bool visit[105][105];
int ans;

int sx,sy,r,c;

void dfs(int ux,int uy)
{
    ans++;
    for(int i=0; i<8; i++)
    {
        int vx=ux+xx[i];
        int vy=uy+yy[i];

        if(vx<0 || vy<0 || vx>98 || vy>98) continue;

        if(visit[vx][vy]==1 || s[vx][vy]=='L') continue;

        visit[vx][vy]=1;

        dfs(vx,vy);
    }
}


int main()
{
    int tc, len, ro, co;
    scanf("%d", &tc);
    while(tc--)
    {
        scanf("%s", s[0]);
        len=strlen(s[0]);
        for(int i=1; i<len; i++)
        {
            scanf("%s", s[i]);
        }
        while(scanf("%d%d", &ro, &co)==2)
        {
            memset(visit,0,sizeof(visit));
            ans=0;
            if(s[ro-1][co-1]=='W')
            {
                visit[ro-1][co-1]=1;
                dfs(ro-1, co-1);
            }
            printf("%d\n", ans);
        }
        if(tc)
            printf("\n");
    }
    return 0;
}

LightOJ 1238-Power Puff Girls

 
The city of Townsville! This nice city is the home for the power puff girls - Blossom, Bubbles and Buttercup. To introduce their personality we can sing a song:
Blossom, commander and the leader;
Bubbles, she is the joy and the laughter;
Buttercup, she is the toughest fighter.
These super girls defend Townsville from monsters and super villains using their super powers, intelligence. They live in a home in Townsville with the professor who is like their father.
The girls are young now and they don't like to fight the monsters anymore. So, if they are outside their home, they are found shopping. And when they get back to home, they simply watch the TV serials. It's such a horrible fact that the super intelligent girls are wasting their time watching serials that consist of the rivalries between Wives and their Mother in Laws. And when they use computers they are usually found using the facenote (a dangerous1 social networking site).
So, such wonderful girls just became lazy and useless. Often they are seen fighting each other, the comments that can be heard, are like, 'Tulsi is the best.', 'Gopi is better than Rashee.' The professor is quite upset with the girls, and he can't even watch any science show or sports because of these irritating serials.
So, the professor made a plan and asked the girls to go for shopping such that he can watch an important science show in the TV. The girls became very excited and they went out for shopping. But soon they realize that one of their favorite serials will start soon, and they need to get back home for that serial.
To be more specific let's consider the city as a 2D grid. In the grid there are some symbols, the meaning of them are:
1.      '.'         means an empty place
2.      'a'        denotes the position of Blossom
3.      'b'       denotes the position of Bubbles
4.      'c'        denotes the position of Buttercup
5.      'm'      denotes that there is a monster
6.      'h'       denotes their home
7.      '#'       denotes a wall and the girls can't pass through it
The three girls move simultaneously. And in each minute, from their current cells, they can move to any four adjacent cells (North, East, West, South) if the destination cell is neither a wall nor the cell contains a monster. Because they want to get home as soon as possible, they want to avoid the monsters. You can assume that they can move to a common cell if necessary.
Now you are given the information of the city and their positions. You have to find the minimum time when they all are in home.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with a line containing two integers: m and n (4 ≤ m, n ≤ 20), m denotes the number of rows and n denotes the number of columns of the modeled grid. Each of the next m lines contains n characters representing the city.
You can assume that 'a', 'b', 'c', 'h' will occur exactly once in the grid. The outer boundaries will always be marked by '#'.

Output

For each case, print the case number and the minimum time needed when they all are in their home. You can assume that a solution will always exist.

Sample Input

Output for Sample Input

2
6 8
########
#...c..#
#......#
#.a.h.b#
#......#
########
5 9
#########
#mmm...c#
#ma.h####
#m....b.#
#########
Case 1: 2
Case 2: 4


Analysis:

As we have to find out minimum time, so we can apply bfs algorithm here. As one super girl can visit the path witch was visited by other super girl, everytime we have to set our memory of array, visit and array, dis to zero.  

Solution: 

#include<bits/stdc++.h>
using namespace std;
int xx[]= {1,-1,0,0};
int yy[]= {0,0,1,-1};
char s[50][50];
int r, c;
bool visit[50][50];
int dis[50][50];
queue <int> q1;
queue <int> q2;

int bfs(int ux, int uy)
{
    int ux1, uy1, vx1, vy1;
    q1.push(ux);
    q2.push(uy);
    visit[ux][uy]=1;
    while(!q1.empty() && !q2.empty())
    {
        ux1=q1.front();
        uy1=q2.front();
        q1.pop();
        q2.pop();
        if(s[ux1][uy1]=='h')
        {
            return dis[ux1][uy1]; //destination found
        }
        for(int i=0; i<4; i++)
        {
            int vx=ux1+xx[i];
            int vy=uy1+yy[i];
            if(vx<0 || vy<0 || vx>=r || vy>=c)
                continue;

            if(visit[vx][vy]==1 || s[vx][vy]=='#' || s[vx][vy]=='m')
                continue;

            visit[vx][vy]=1;
            q1.push(vx);
            q2.push(vy);
            dis[vx][vy]=dis[ux1][uy1]+1;
        }
    }
}


int main()
{

    int i, j, d1, d2, d3, ax, ay, bx, by, cx, cy, sum, t_case, kl=0;
    scanf("%d", &t_case);
    while(t_case--)
    {
        scanf("%d%d", &r, &c);
        sum=0;
        memset(s, 0, sizeof(s));
        for(i=0; i<r; i++)
        {
            scanf("%s",s[i]);
            for(j=0; j<c; j++)
            {
                if(s[i][j]=='a')
                {
                    ax=i;
                    ay=j;
                }
                if(s[i][j]=='b')
                {
                    bx=i;
                    by=j;
                }
                if(s[i][j]=='c')
                {
                    cx=i;
                    cy=j;
                }

            }
        }
        while(!q1.empty() && !q2.empty())
        {
            q1.pop();
            q2.pop();
        }
        memset(dis, 0, sizeof(dis));
        memset(visit, 0, sizeof(visit));
        d1=bfs(ax, ay);
        if(d1>sum)
            sum=d1;
        while(!q1.empty() && !q2.empty())
        {
            q1.pop();
            q2.pop();
        }
        memset(dis, 0, sizeof(dis));
        memset(visit, 0, sizeof(visit));
        d2=bfs(bx, by);
        if(d2>sum)
            sum=d2;
        while(!q1.empty() && !q2.empty())
        {
            q1.pop();
            q2.pop();
        }
        memset(dis, 0, sizeof(dis));
        memset(visit, 0, sizeof(visit));
        d3=bfs(cx, cy);
        if(d3>sum)
            sum=d3;
        printf("Case %d: %d\n", ++kl, sum);
    }

    return 0;
}