| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
这题用回溯做不行么?我怎么总是runtime error 啊?哪位大侠帮着看看!#include <iostream>
#include <string.h>
using namespace std;
struct hol{
int r, c;
};
struct hol h[9];
bool lair[21][21];
int n, m, L, K, head, tail;
int ans;
const int maxint = 99999999;
void modify(int newheadr, int newheadc, int tailr, int tailc)
{
lair[newheadr][newheadc] = 1;
lair[tailr][tailc] = 0;
h[tail].r = newheadr;
h[tail].c = newheadc;
tail--;
if (tail < 1)
tail = L;
head--;
if (head < 1)
head = L;
}
void retray(int newheadr, int newheadc, int tailr, int tailc)
{
lair[newheadr][newheadc] = 0;
lair[tailr][tailc] = 1;
tail++;
if (tail > L)
tail = 1;
head++;
if (head > L)
head = 1;
}
void backtrack(int cur_len)
{
int headr = h[head].r, headc = h[head].c;
int tailr = h[tail].r, tailc = h[tail].c;
int tempr, tempc;
if (headr == 1 && headc == 2 && lair[1][1] == 0 || headr == 2 && headc == 1 && lair[1][1] == 0)
{
cur_len++;
if (cur_len < ans)
ans = cur_len;
return;
}
if (headr - 1 >= 1 && lair[headr-1][headc] != 1 && cur_len + headr-1 + headc-1 < ans)
{
tempr = h[tail].r;
tempc = h[tail].c;
cur_len++;
modify(headr-1, headc, tailr, tailc);
backtrack(cur_len);
cur_len--;
retray(headr-1, headc, tailr, tailc);
h[tail].r = tempr;
h[tail].c = tempc;
}
if (headc - 1 >= 1 && lair[headr][headc-1] != 1 && cur_len + headr-1 + headc-1 < ans)
{
tempr = h[tail].r;
tempc = h[tail].c;
cur_len++;
modify(headr, headc-1, tailr, tailc);
backtrack(cur_len);
cur_len--;
retray(headr, headc-1, tailr, tailc);
h[tail].r = tempr;
h[tail].c = tempc;
}
if (headc + 1 <= m && lair[headr][headc+1] != 1 && cur_len + headr + headc < ans)
{
tempr = h[tail].r;
tempc = h[tail].c;
cur_len++;
modify(headr, headc+1, tailr, tailc);
backtrack(cur_len);
cur_len--;
retray(headr, headc+1, tailr, tailc);
h[tail].r = tempr;
h[tail].c = tempc;
}
if (headr + 1 <= n && lair[headr+1][headc] != 1 && cur_len + headr + headc < ans)
{
tempr = h[tail].r;
tempc = h[tail].c;
cur_len++;
modify(headr+1, headc, tailr, tailc);
backtrack(cur_len);
cur_len--;
retray(headr+1, headc, tailr, tailc);
h[tail].r = tempr;
h[tail].c = tempc;
}
}
int main()
{
int r, c, T = 0;
while (scanf("%d%d%d", &n, &m, &L) && (n || m || L))
{
T++;
memset(lair, 0, sizeof(0));
for (int i = 1; i <= L; i++)
{
scanf("%d%d", &r, &c);
h[i].r = r;
h[i].c = c;
lair[r][c] = 1;
}
scanf("%d", &K);
for (int i = 1; i <= K; i++)
{
scanf("%d%d", &r, &c);
lair[r][c] = 1;
}
if (n == 1 && m == 1)
{
printf("Case %d: 0\n", T);
continue;
}
ans = maxint;
head = 1; tail = L;
backtrack(0);
if (ans == maxint)
printf("Case %d: -1\n", T);
else
printf("Case %d: %d\n", T, ans);
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator