大菜鸡的图论之旅-[kuangbin带你飞]专题一 简单搜索

大菜鸡的图论之旅-[kuangbin带你飞]专题一 简单搜索


拖了一万年,可算把这个专题做完了。
再拖拖拉拉我是狗。

A POJ 1321 棋盘问题

Problem Description

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

Input

输入含有多组测试数据。
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。

Output

对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

Sample Input

2 1
#.
.#
4 4
…#
…#.
.#…
#…
-1 -1

Sample Output

2
1


Code

#include <iostream>
#include <cstring>

using namespace std;

int ans;
int cnt;
int n,k;
int visited[10];
char state[10][10];

void dfs(int t)
{
    if(cnt==k)
    {
        ans++;
        return;
    }
    if(t>=n)
        return;
    for(int i=0; i<n; i++)
    {
        if(state[t][i]=='#'&&visited[i]==0)
        {
            cnt++;
            visited[i]++;
            dfs(t+1);
            cnt--;
            visited[i]=0;
        }
    }
    dfs(t+1);
}

int main()
{
    while(cin>>n>>k)
    {
        if(n==-1&&k==-1)
            break;
        memset(visited,0,sizeof(visited));
        ans=0;
        cnt=0;
        for(int i=0; i<n; i++)
        {
            cin>>state[i];
        }
        dfs(0);
        cout<<ans<<endl;
    }
    return 0;
}

B POJ 2251 Dungeon Master

Problem Description

You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take?

Input

The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a ‘#’ and empty cells are represented by a ‘.’. Your starting position is indicated by ‘S’ and the exit by the letter ‘E’. There’s a single blank line after each level. Input is terminated by three zeroes for L, R and C.

Output

Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s).
where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line
Trapped!

Sample Input

3 4 5
S…
.###.
.##…
###.#

##.##
##…

#.###
####E

1 3 3
S##
#E#

0 0 0

Sample Output

Escaped in 11 minute(s).
Trapped!


Code

#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>

using namespace std;

const int dir[6][3]= {1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};

struct S
{
    int x,y,z;
    int cnt;
};

int main()
{
    int l,r,c;
    while(cin>>l>>r>>c)
    {
        getchar();
        if(l==0&&r==0&&c==0)
            break;
        char state[32][32][32];
        int vis[32][32][32];
        memset(vis,0,sizeof(vis));
        queue <S> Q;
        S start;
        start.cnt=0;
        S endd;
        endd.cnt=-1;
        for(int i=0; i<l; i++)
        {
            for(int j=0; j<r; j++)
            {
                for(int k=0; k<c; k++)
                {
                    scanf("%c",&state[i][j][k]);
                    if(state[i][j][k]=='S')
                    {
                        start.x=i;
                        start.y=j;
                        start.z=k;
                    }
                    else if(state[i][j][k]=='E')
                    {
                        endd.x=i;
                        endd.y=j;
                        endd.z=k;
                    }
                    else if(state[i][j][k]=='#')
                    {
                        vis[i][j][k]=1;
                    }
                }
                getchar();
            }
            getchar();
        }
        vis[start.x][start.y][start.z]=1;
        Q.push(start);
        while(!Q.empty())
        {
            S now=Q.front();
            if(now.x==endd.x&&now.y==endd.y&&now.z==endd.z)
            {
                endd.cnt=now.cnt;
                break;
            }
            for(int i=0; i<6; i++)
            {
                S next;
                next.x=now.x+dir[i][0];
                next.y=now.y+dir[i][1];
                next.z=now.z+dir[i][2];
                if(next.x>=0&&next.x<l&&next.y>=0&&next.y<r&&next.z>=0&&next.z<c&&vis[next.x][next.y][next.z]==0)
                {
                    next.cnt=now.cnt+1;
                    Q.push(next);
                    vis[next.x][next.y][next.z]=1;
                }
            }
            Q.pop();
        }
        if(endd.cnt==-1)
        {
            cout<<"Trapped!"<<endl;
        }
        else
        {
            cout<<"Escaped in "<<endd.cnt<<" minute(s)."<<endl;
        }
    }
    return 0;
}

C POJ 3278 Catch That Cow

Problem Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.


Code

#include<iostream>
#include<algorithm>
#include<queue>
#include <cstring>

using namespace std;

const int MAX=100005;

int main()
{
    int visited[MAX],n,k;
    while(cin>>n>>k)
    {
        memset(visited,0x3f3f3f3f,sizeof(visited));
        queue<int> q;
        q.push(n);
        visited[n]=0;
        while(!q.empty())
        {
            int now=q.front();
            if(now==k)
                break;
            int x;
            x=now+1;
            if(x>=0&&x<MAX&&visited[now]+1<visited[x])
            {
                visited[x]=visited[now]+1;
                q.push(x);
            }
            x=now-1;
            if(x>=0&&x<MAX&&visited[now]+1<visited[x])
            {
                visited[x]=visited[now]+1;
                q.push(x);
            }
            x=now*2;
            if(x>=0&&x<MAX&&visited[now]+1<visited[x])
            {
                visited[x]=visited[now]+1;
                q.push(x);
            }
            q.pop();
        }
        cout<<visited[k]<<endl;
    }
    return 0;
}

D POJ 3279 Fliptile

Problem Description

Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M × N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which is colored black on one side and white on the other side.
As one would guess, when a single white tile is flipped, it changes to black; when a single black tile is flipped, it changes to white. The cows are rewarded when they flip the tiles so that each tile has the white side face up. However, the cows have rather large hooves and when they try to flip a certain tile, they also flip all the adjacent tiles (tiles that share a full edge with the flipped tile). Since the flips are tiring, the cows want to minimize the number of flips they have to make.
Help the cows determine the minimum number of flips required, and the locations to flip to achieve that minimum. If there are multiple ways to achieve the task with the minimum amount of flips, return the one with the least lexicographical ordering in the output when considered as a string. If the task is impossible, print one line with the word “IMPOSSIBLE”.

Input

Line 1: Two space-separated integers: M and N
Lines 2…M+1: Line i+1 describes the colors (left to right) of row i of the grid with N space-separated integers which are 1 for black and 0 for white

Output

Lines 1…M: Each line contains N space-separated integers, each specifying how many times to flip that particular location.

Sample Input

4 4
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1

Sample Output

0 0 0 0
1 0 0 1
1 0 0 1
0 0 0 0


Code

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

typedef long long ll;

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)

const int N=20;

int mapp[N][N];
int state[N][N];
int ans[N][N];
int fir_lin[N];
int out[N][N];
int n,m;

ll quick_pow(ll a,ll b)
{
    ll ret=1;
    while(b)
    {
        if(b&1) ret=ret*a;
        a=a*a;
        b>>=1;
    }
    return ret;
}

void turn(int x,int y)
{
    state[x][y]^=1;
    state[x-1][y]^=1;
    state[x+1][y]^=1;
    state[x][y-1]^=1;
    state[x][y+1]^=1;
}

void cop()
{
    rep(i,1,n)
    {
        rep(j,1,m)
        {
            out[i][j]=ans[i][j];
        }
    }
}

int main()
{
    scanf("%d%d",&n,&m);
    rep(i,1,n) rep(j,1,m) scanf("%d",&mapp[i][j]);
    int maxn=quick_pow(2,m);
    int minn=0x3f3f3f3f;
    rep(cnt,0,maxn)
    {
        int ccnt=0;
        memset(ans,0,sizeof(ans));
        rep(i,1,n) rep(j,1,m) state[i][j]=mapp[i][j];
        int cntt=cnt;
        per(i,m,1)
        {
            ans[1][i]=cntt%2;
            if(ans[1][i]==1) turn(1,i),ccnt++;
            cntt/=2;
        }
        rep(i,2,n)
        {
            rep(j,1,m)
            {
                if(state[i-1][j]==1)
                {
                    ans[i][j]=1;
                    ccnt++;
                    turn(i,j);
                }
            }
        }
        int flag=1;
        rep(j,1,m)
        {
            if(state[n][j]==1)
            {
                flag=0;
                break;
            }
        }
        if(flag==1&&ccnt<minn)
        {
            cop();
            minn=ccnt;
        }
    }
    if(minn<=0x3f3f3f3f-0x3f)
    {
        rep(i,1,n)
        {
            rep(j,1,m)
            {
                printf("%d%c",out[i][j]," \n"[j==m]);
            }
        }
    }
    else
        printf("IMPOSSIBLE\n");
    return 0;
}


E POJ 1426 Find The Multiple

Problem Description

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.

Input

The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.

Output

For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.

Sample Input

2
6
19
0

Sample Output

10
100100100100100100
111111111111111111


Code

#include <iostream>

using namespace std;

unsigned long long n;

const unsigned long long INF = 0x3f3f3f3f3f3f3f3f;

int flag=0;

void dfs(unsigned long long x,unsigned long long num)
{
    if(flag==1||x >= ((unsigned long long) INF))
        return;
    if(x%n==0)
    {
        flag=1;
        cout<<x<<endl;
        return ;
    }
    else
    {
        dfs(x*10+1,num+1);
        dfs(x*10,num+1);
    }
}

int main()
{
    while(cin>>n)
    {
        flag=0;
        if(n==0)
            break;
        dfs(1,0);
    }
    return 0;
}

F POJ 3126 Prime Path

Problem Description

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.
— It is a matter of security to change such things every now and then, to keep the enemy in the dark.
— But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
— I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door.
— No, it’s not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime!
— I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds.
— Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime.
Now, the minister of finance, who had been eavesdropping, intervened.
— No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
— Hmm, in that case I need a computer program to minimize the cost. You don’t know some very cheap software gurus, do you?
— In fact, I do. You see, there is this programming contest going on… Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.

Input

One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).

Output

One line for each case, either with a number stating the minimal cost or containing the word Impossible.

Sample Input

3
1033 8179
1373 8017
1033 1033

Sample Output

6
7
0


Code

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int MAXN=10010;
int prime[MAXN+5];

struct S
{
    string str;
    int cnt;
};

void init()
{
    prime[0]=prime[1]=1;
    for(int i=2;i<MAXN;i++)
    {
        if(i>MAXN/i) continue;
        for(int j=i*i;j<MAXN;j+=i)
        {
            prime[j]=1;
        }
    }
}

int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        memset(prime,0,sizeof(prime));
        init();
        S start,endd;
        cin>>start.str>>endd.str;
        start.cnt=0;
        endd.cnt=0;
        queue <S> Q;
        Q.push(start);
        prime[(start.str[3]-'0')+(start.str[2]-'0')*10+(start.str[1]-'0')*100+(start.str[0]-'0')*1000]=1;
        int flag=0;
        while(!Q.empty())
        {
            S now=Q.front();
            if(now.str==endd.str)
            {
                flag=1;
                endd.cnt=now.cnt;
                break;
            }
            S next;
            for(int j=0; j<4; j++)
            {
                for(char i='0'; i<='9'; i++)
                {
                    next.str=now.str;
                    if(now.str[j]==i||(j==0&&i=='0'))
                        continue;
                    else
                    {
                        next.str[j]=i;
                        next.cnt=now.cnt+1;
                        int num=0;
                        num=(next.str[3]-'0')+(next.str[2]-'0')*10+(next.str[1]-'0')*100+(next.str[0]-'0')*1000;
                        if(prime[num]==0)
                        {
                            Q.push(next);
                            prime[num]=1;
                        }
                    }
                }
            }
            Q.pop();
        }
        if(flag==1)
            cout<<endd.cnt<<endl;
        else
            cout<<"Impossible"<<endl;
    }
    return 0;
}

F POJ 3087 Shuffle’m Up

Problem Description

A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by starting with two stacks of poker chips, S1 and S2, each stack containing C chips. Each stack may contain chips of several different colors.
The actual shuffle operation is performed by interleaving a chip from S1 with a chip from S2 as shown below for C = 5:
在这里插入图片描述
The single resultant stack, S12, contains 2 * C chips. The bottommost chip of S12 is the bottommost chip from S2. On top of that chip, is the bottommost chip from S1. The interleaving process continues taking the 2nd chip from the bottom of S2 and placing that on S12, followed by the 2nd chip from the bottom of S1 and so on until the topmost chip from S1 is placed on top of S12.
After the shuffle operation, S12 is split into 2 new stacks by taking the bottommost C chips from S12 to form a new S1 and the topmost C chips from S12 to form a new S2. The shuffle operation may then be repeated to form a new S12.
For this problem, you will write a program to determine if a particular resultant stack S12 can be formed by shuffling two stacks some number of times.

Input

The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.
Each dataset consists of four lines of input. The first line of a dataset specifies an integer C, (1 ≤ C ≤ 100) which is the number of chips in each initial stack (S1 and S2). The second line of each dataset specifies the colors of each of the C chips in stack S1, starting with the bottommost chip. The third line of each dataset specifies the colors of each of the C chips in stack S2 starting with the bottommost chip. Colors are expressed as a single uppercase letter (A through H). There are no blanks or separators between the chip colors. The fourth line of each dataset contains 2 * C uppercase letters (A through H), representing the colors of the desired result of the shuffling of S1 and S2 zero or more times. The bottommost chip’s color is specified first.

Output

Output for each dataset consists of a single line that displays the dataset number (1 though N), a space, and an integer value which is the minimum number of shuffle operations required to get the desired resultant stack. If the desired result can not be reached using the input for the dataset, display the value negative 1 (−1) for the number of shuffle operations.

Sample Input

2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC

Sample Output

1 2
2 -1


Code

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <map>

using namespace std;

typedef long long ll;

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)

int main()
{
    int T;
    scanf("%d", &T);
    rep(cas,1,T)
    {
        int n;
        cin >> n;
        string s1,s2;
        cin >> s1 >> s2;
        string ans;
        cin >> ans;
        string str = s1 + s2;
        string fir = str;
        int cnt=0;
        map<string,int> M;
        while(str != ans && !M.count(str))
        {
            M[str]=1;
            cnt++;
            string temp = str;
            str = "";
            rep(i,0,n-1)
            {
                str += temp[n+i];
                str += temp[i];
            }
        }
        if(str == ans)
        {
            printf("%d %d\n", cas, cnt);
        }
        else
        {
            printf("%d %d\n", cas, -1);
        }
    }
    return 0;
}

H POJ 3414 Pots

Problem Description

You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
1.FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
2.DROP(i) empty the pot i to the drain;
3.POUR(i,j) pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.

Input

On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).

Output

The first line of the output must contain the length of the sequence of operations K. The following K lines must each describe one operation. If there are several sequences of minimal length, output any one of them. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.

Sample Input

3 5 4

Sample Output

6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)


Code

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <map>
#include <queue>

using namespace std;

typedef long long ll;

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)

struct S
{
    int x,y;
};

map<pair<int,int>,pair<pair<int,int>,int> > vis;
vector<int> G;

int main()
{
    int a,b,c;
    scanf("%d%d%d",&a,&b,&c);
    queue<S> Q;
    Q.push({a,0});
    Q.push({0,b});
    vis[make_pair(a,0)]=make_pair(make_pair(-1,-1),-1);
    vis[make_pair(0,b)]=make_pair(make_pair(-1,-1),-1);
    while(!Q.empty())
    {
        S now=Q.front();
        Q.pop();
        if(now.x==c||now.y==c)
        {
            int x=now.x,y=now.y;
            while(vis[make_pair(x,y)].second!=-1)
            {
                G.push_back(vis[make_pair(x,y)].second);
                int xx=x;
                int yy=y;
                x=vis[make_pair(xx,yy)].first.first;
                y=vis[make_pair(xx,yy)].first.second;
            }
            if(x==0)
                G.push_back(2);
            else
                G.push_back(1);
            break;
        }
        if(!vis.count(make_pair(a,now.y)))
        {
            Q.push({a,now.y});
            vis[make_pair(a,now.y)]=make_pair(make_pair(now.x,now.y),1);
        }
        if(!vis.count(make_pair(now.x,b)))
        {
            Q.push({now.x,b});
            vis[make_pair(now.x,b)]=make_pair(make_pair(now.x,now.y),2);
        }
        if(!vis.count(make_pair(0,now.y)))
        {
            Q.push({0,now.y});
            vis[make_pair(0,now.y)]=make_pair(make_pair(now.x,now.y),3);
        }
        if(!vis.count(make_pair(now.x,0)))
        {
            Q.push({now.x,0});
            vis[make_pair(now.x,0)]=make_pair(make_pair(now.x,now.y),4);
        }
        if(!vis.count(make_pair(now.x-min(now.x,b-now.y),now.y+min(now.x,b-now.y))))
        {
            Q.push({now.x-min(now.x,b-now.y),now.y+min(now.x,b-now.y)});
            vis[make_pair(now.x-min(now.x,b-now.y),now.y+min(now.x,b-now.y))]=make_pair(make_pair(now.x,now.y),5);
        }
        if(!vis.count(make_pair(now.x+min(now.y,a-now.x),now.y-min(now.y,a-now.x))))
        {
            Q.push({now.x+min(now.y,a-now.x),now.y-min(now.y,a-now.x)});
            vis[make_pair(now.x+min(now.y,a-now.x),now.y-min(now.y,a-now.x))]=make_pair(make_pair(now.x,now.y),6);
        }
    }
    int len=G.size();
    if(len==0)
    {
        printf("impossible\n");
        return 0;
    }
    printf("%d\n",len);
    per(i,len-1,0)
    {
        if(G[i]==1)
            printf("FILL(1)\n");
        else if(G[i]==2)
            printf("FILL(2)\n");
        else if(G[i]==3)
            printf("DROP(1)\n");
        else if(G[i]==4)
            printf("DROP(2)\n");
        else if(G[i]==5)
            printf("POUR(1,2)\n");
        else if(G[i]==6)
            printf("POUR(2,1)\n");
    }
    return 0;
}

I FZU 2150 Fire Game

Problem Description

Fat brother and Maze are playing a kind of special (hentai) game on an N*M board (N rows, M columns). At the beginning, each grid of this board is consisting of grass or just empty and then they start to fire all the grass. Firstly they choose two grids which are consisting of grass and set fire. As we all know, the fire can spread among the grass. If the grid (x, y) is firing at time t, the grid which is adjacent to this grid will fire at time t+1 which refers to the grid (x+1, y), (x-1, y), (x, y+1), (x, y-1). This process ends when no new grid get fire. If then all the grid which are consisting of grass is get fired, Fat brother and Maze will stand in the middle of the grid and playing a MORE special (hentai) game. (Maybe it’s the OOXX game which decrypted in the last problem, who knows.)
You can assume that the grass in the board would never burn out and the empty grid would never get fire.
Note that the two grids they choose can be the same.

Input

The first line of the date is an integer T, which is the number of the text cases.

Then T cases follow, each case contains two integers N and M indicate the size of the board. Then goes N line, each line with M character shows the board. “#” Indicates the grass. You can assume that there is at least one grid which is consisting of grass in the board.
1 <= T <=100, 1 <= n <=10, 1 <= m <=10

Output

For each case, output the case number first, if they can play the MORE special (hentai) game (fire all the grass), output the minimal time they need to wait after they set fire, otherwise just output -1. See the sample input and output for more details.

Sample Input

4
3 3
.#.

.#.
3 3
.#.
#.#
.#.
3 3

#.#

3 3

…#
#.#

Sample Output

Case 1: 1
Case 2: -1
Case 3: 0
Case 4: 2


Code

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;

typedef long long ll;

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)

const int N=15;

int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};

struct S
{
    int x,y;
    int cnt ;
};

vector<S> v;

char mp[N][N];
int vis[N][N];
int n,m;

int BFS(S a,S b)
{
    memset(vis,0,sizeof(vis));
    queue<S> q;
    vis[a.x][a.y]=vis[b.x][b.y]=1;
    a.cnt=0,b.cnt=0;
    q.push(a),q.push(b);
    int ans = 0x3f3f3f3f;
    int cas = 1;
    while(!q.empty())
    {
        a=q.front();
        q.pop();
        ans=a.cnt;
        rep(i,0,3)
        {
            b.x=a.x+dx[i];
            b.y=a.y+dy[i];
            b.cnt=a.cnt+1;
            if(b.x>0&&b.y>0&&b.x<=n&&b.y<=m&&vis[b.x][b.y]==0&&mp[b.x][b.y]=='#')
            {
                vis[b.x][b.y] = 1;
                q.push(b);
            }
        }
    }
    return ans;
}

void print()
{
    rep(i,1,n)
    {
        rep(j,1,m)
        {
            printf("%c ",mp[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    rep(cas,1,T)
    {
        v.clear();
        scanf("%d%d",&n,&m);
        rep(i,1,n)
        {
            getchar();
            rep(j,1,m)
            {
                scanf("%c",&mp[i][j]);
                if(mp[i][j]=='#')
                    v.push_back((S){i,j,0});
            }
        }
        int ans=0x3f3f3f3f;
        for(int i=0;i<v.size();i++)
        {
            for(int j=i;j<v.size();j++)
            {
                int tmp=BFS(v[i],v[j]);
                bool ok=true;
                for(int k=1;k<=n;k++)
                {
                    for(int f=1;f<=m;f++)
                    {
                        if(vis[k][f]==0&&mp[k][f]=='#')
                        {
                            ok=false;
                            break;
                        }
                    }
                    if(!ok) break;
                }
                if(ok) ans=min(ans,tmp);
            }
        }
        printf("Case %d: ",cas);
        if(ans==0x3f3f3f3f)
            puts("-1");
        else
            printf("%d\n",ans);
    }
    return 0;
}

J UVA 11624 Fire!

Problem Description

Joe works in a maze. Unfortunately, portions of the maze have
caught on fire, and the owner of the maze neglected to create a fire
escape plan. Help Joe escape the maze.
Given Joe’s location in the maze and which squares of the maze
are on fire, you must determine whether Joe can exit the maze before
the fire reaches him, and how fast he can do it.
Joe and the fire each move one square per minute, vertically or
horizontally (not diagonally). The fire spreads all four directions
from each square that is on fire. Joe may exit the maze from any
square that borders the edge of the maze. Neither Joe nor the fire
may enter a square that is occupied by a wall.

Input

The first line of input contains a single integer, the number of test
cases to follow. The first line of each test case contains the two
integers R and C, separated by spaces, with 1 ≤ R, C ≤ 1000. The
following R lines of the test case each contain one row of the maze. Each of these lines contains exactly
C characters, and each of these characters is one of:
• #, a wall
• ., a passable square
• J, Joe’s initial position in the maze, which is a passable square
• F, a square that is on fire
There will be exactly one J in each test case.

Output

For each test case, output a single line containing ‘IMPOSSIBLE’ if Joe cannot exit the maze before the
fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.

Sample Input

2
4 4

#JF#
#…#
#…#
3 3

#J.
#.F

Sample Output

3
IMPOSSIBLE


Code

#include <iostream>
#include <cstring>
#include <queue>
#include <cmath>

using namespace std;

const int dir[4][2]={1,0,0,1,-1,0,0,-1};

char state[1005][1005];
int vis[1005][1005];

struct S
{
    int x,y;
    int cnt;
};

int main()
{
    int t;
     cin>>t;
    while(t--)
    {
        memset(vis,0,sizeof(vis));
        int r,c;
        cin>>r>>c;
        S start,fire;
        queue<S> QQ;
        for(int i=0;i<r;i++)
        {
            cin>>state[i];
            for(int j=0;j<c;j++)
            {
                if(state[i][j]=='#')
                {
                    vis[i][j]=-1;
                }
                else if(state[i][j]=='J')
                {
                    start.x=i;
                    start.y=j;
                    start.cnt=0;
                    vis[i][j]=-1;
                }
                else if(state[i][j]=='F')
                {
                    fire.x=i;
                    fire.y=j;
                    fire.cnt=0;
                    vis[i][j]=-1;
                    QQ.push(fire);
                }
            }
        }
        while(!QQ.empty())
        {
            S now,next;
            now=QQ.front();
            for(int i=0;i<4;i++)
            {
                next.x=now.x+dir[i][0];
                next.y=now.y+dir[i][1];
                next.cnt=now.cnt+1;
                if(next.x>=0&&next.x<r&&next.y>=0&&next.y<c&&vis[next.x][next.y]==0)
                {
                    QQ.push(next);
                    vis[next.x][next.y]=next.cnt;
                }
            }
            QQ.pop();
        }
        queue<S> Q;
        Q.push(start);
        int flag=0;
        while(!Q.empty())
        {
            S now,next;
            now=Q.front();
            if(now.x==0||now.x==r-1||now.y==0||now.y==c-1)
            {
                flag=1;
                fire.cnt=now.cnt+1;
                break;
            }
            for(int i=0;i<4;i++)
            {
                next.x=now.x+dir[i][0];
                next.y=now.y+dir[i][1];
                next.cnt=now.cnt+1;
                if(next.x>=0&&next.x<r&&next.y>=0&&next.y<c&&(next.cnt<vis[next.x][next.y]||vis[next.x][next.y]==0))
                {
                    Q.push(next);
                    vis[next.x][next.y]=1;
                }
            }
            Q.pop();
        }
        if(flag==0)
        {
            cout<<"IMPOSSIBLE"<<endl;
        }
        else
        {
            cout<<fire.cnt<<endl;
        }
    }
    return 0;
}

K POJ 3984 迷宫问题

Problem Description

定义一个二维数组:

int maze[5][5] ={
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)


Code

#include <iostream>
#include <cstring>
#include <queue>
#include <cstdio>

using namespace std;

const int N=5;
const int dir[4][2]={1,0,0,1,-1,0,0,-1};

int state[N][N];
int vis[N][N];

struct S
{
    int x,y;
};

int main()
{
    memset(vis,0,sizeof(vis));
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<N;j++)
        {
            cin>>state[i][j];
            vis[i][j]=state[i][j];
        }
    }
    S start;
    start.x=0;
    start.y=0;
    vis[start.x][start.y]=1;
    queue <S> Q;
    Q.push(start);
    S pre[N][N];
    pre[0][0].x=-1;
    pre[0][0].y=-1;
    while(!Q.empty())
    {
        S now=Q.front();
        if(now.x==4&&now.y==4)
        {
            break;
        }
        S next;
        for(int i=0;i<4;i++)
        {
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            if(next.x>=0&&next.x<N&&next.y>=0&&next.y<N&&vis[next.x][next.y]==0)
            {
                Q.push(next);
                pre[next.x][next.y].x=now.x;
                pre[next.x][next.y].y=now.y;
                vis[next.x][next.y]=1;
            }
        }
        Q.pop();
    }
    int x=4,y=4;
    S ans[25];
    int cnt=0;
    while(pre[x][y].x!=-1&&pre[x][y].y!=-1)
    {
        int xx=x,yy=y;
        ans[cnt].x=x;
        ans[cnt++].y=y;
        x=pre[xx][yy].x;
        y=pre[xx][yy].y;
    }
    cout<<"(0, 0)"<<endl;
    for(int i=cnt-1;i>=0;i--)
    {
        printf("(%d, %d)\n",ans[i].x,ans[i].y);
    }
    return 0;
}

L POJ 1241 Oil Deposits

Problem Description

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

Input

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either ‘*’, representing the absence of oil, or ‘@’, representing an oil pocket.

Output

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

Sample Input

1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0

Sample Output

0
1
2
2


Code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

char state[1005][1005];
int visited[1005][1005];
int dir[8][2]= {0,1,0,-1,1,0,-1,0,1,1,1,-1,-1,1,-1,-1};
int counter;

struct S
{
    int x,y;
} ;

S s;

int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
            break;
        memset(visited,1,sizeof(visited));
        int maxn=0;
        counter=0;
        int ans=0;
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                state[i][j]='*';
            }
        }
        for(int i=0; i<n; i++)
        {
            cin>>state[i];
        }
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(state[i][j]!='*')
                {
                    visited[i][j]=0;
                    counter++;
                }
            }
        }

        queue <S> q;

        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(visited[i][j]==0)
                {
                    ans++;
                    int sum=0;
                    s.x=i;
                    s.y=j;
                    q.push(s);
                    visited[i][j]=1;
                    S now,next;
                    while(!q.empty())
                    {
                        now=q.front();
                        if(state[now.x][now.y]=='@')
                            sum++;
                        for(int ii=0; ii<8; ii++)
                        {
                            next.x=now.x+dir[ii][0];
                            next.y=now.y+dir[ii][1];
                            if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&visited[next.x][next.y]==0)
                            {
                                q.push(next);
                                visited[next.x][next.y]=1;
                            }
                        }
                        q.pop();
                        if(sum>maxn)
                            maxn=sum;
                    }
                }
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

M HDU 1495 非常可乐

Problem Description

大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。

Input

三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。

Output

如果能平分的话请输出最少要倒的次数,否则输出"NO"。

Sample Input

7 4 3
4 1 3
0 0 0

Sample Output

NO
3


Code

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

int vis[105][105][105];

struct S
{
    int dri[3];
    int step;
};

int main()
{
    int st[3];
    while(cin>>st[0]>>st[1]>>st[2])
    {
        if(st[0]==0||st[1]==0||st[2]==0)
            break;
        if(st[0]%2==1)
        {
            cout<<"NO"<<endl;
            continue;
        }
        memset(vis,0,sizeof(vis));
        if(st[1]<st[2])
            swap(st[1],st[2]);
        S start;
        start.dri[0]=st[0];
        start.dri[1]=0;
        start.dri[2]=0;
        start.step=0;
        queue <S> Q;
        Q.push(start);
        int fflag=0;
        while(!Q.empty())
        {
            S now=Q.front();
            int flag=0;
            for(int i=0;i<3;i++)
            {
                if(now.dri[i]==st[0]/2)
                {
                    flag++;
                    fflag=1;
                }
            }
            if(flag==2)
            {
                cout<<now.step<<endl;
                break;
            }
            for(int i=0;i<3;i++)
            {
                for(int j=0;j<3;j++)
                {
                    if(i==j||now.dri[i]==0)
                        continue;
                    S next=now;
                    if(st[j]-now.dri[j]>=now.dri[i])
                    {
                        next.dri[j]=now.dri[j]+now.dri[i];
                        next.dri[i]=0;
                    }
                    else
                    {
                        next.dri[j]=st[j];
                        next.dri[i]=now.dri[i]-(next.dri[j]-now.dri[j]);
                    }
                    next.step=now.step+1;
                    if(vis[next.dri[0]][next.dri[1]][next.dri[2]]!=1)
                    {
                        Q.push(next);
                        vis[next.dri[0]][next.dri[1]][next.dri[2]]=1;
                    }
                }
            }
            Q.pop();
        }
        if(fflag==0)
        {
            cout<<"NO"<<endl;
        }
    }
    return 0;
}


N HDU 2612 Find a way

Problem Description

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

Input

The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

Output

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

Sample Input

4 4
Y.#@

.#…
@…M
4 4
Y.#@

.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#

Sample Output

66
88
66


Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

const int dir[4][2]= {1,0,0,1,-1,0,0,-1};

char state[205][205];
int vis[205][205];

struct S
{
    int x,y;
    int len;
};

int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        for(int i=0; i<n; i++)
        {
            cin>>state[i];
        }
        S kfc[40005];
        S yi,me;
        int cntkfc=0;
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(state[i][j]=='@')
                {
                    kfc[cntkfc].x=i;
                    kfc[cntkfc++].y=j;
                }
                else if(state[i][j]=='Y')
                {
                    yi.x=i;
                    yi.y=j;
                }
                else if(state[i][j]=='M')
                {
                    me.x=i;
                    me.y=j;
                }
            }
        }
        int minn=0x3f3f3f3f;
        while(cntkfc--)
        {
            int flag=0;
            memset(vis,0,sizeof(vis));
            for(int i=0; i<n; i++)
            {
                for(int j=0; j<m; j++)
                {
                    if(state[i][j]=='#')
                    {
                        vis[i][j]=1;
                    }
                }
            }
            queue<S> Q;
            S start;
            start.x=kfc[cntkfc].x;
            start.y=kfc[cntkfc].y;
            start.len=0;
            vis[start.x][start.y]=1;
            Q.push(start);
            int ans=0;
            while(!Q.empty())
            {
                S now,next;
                now=Q.front();
                if((now.x==yi.x&&now.y==yi.y)||(now.x==me.x&&now.y==me.y))
                {
                    ans+=now.len;
                    flag++;
                }
                if(flag==2)
                {
                    if(ans<minn)
                        minn=ans;
                    break;
                }
                for(int i=0; i<4; i++)
                {
                    next.x=now.x+dir[i][0];
                    next.y=now.y+dir[i][1];
                    next.len=now.len+1;
                    if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&vis[next.x][next.y]==0)
                    {
                        vis[next.x][next.y]=1;
                        Q.push(next);
                    }
                }
                Q.pop();
            }
        }
        cout<<minn*11<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值