您的位置:首页 > 其它

CF 390D:Inna and Sweet Matrix

2014-03-07 01:21 405 查看
这题也不好解释。大意是一个n*m的矩阵,I有k枚糖果,每一枚糖果都会逐一放在(i , j)的格子上,且I从(1,1)到这个格子必须存在一条没有糖果覆盖的路径,否则无法放置。求I放完所有糖果后所需的最小步数,并打印出放每枚糖果的路径。

简单的bfs就行了。

#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <iostream>
using namespace std;

typedef struct cell{
int fx , fy ;
int xx , yy ;
int kk ;
int step ;
}Cell ;

Cell ma[55][55] ;
bool vis[55][55] ;
int n , m , k , sp = 0 ;
queue <Cell> q ;
stack <Cell> candy ;
stack <Cell> path ;

void init() {
for (int i = 0 ; i <= n ; i ++) {
for (int j = 0 ; j <= m ; j ++) {
ma[i][j].xx = i ; ma[i][j].yy = j ;
}
}
}

void bfs() {
while (k) {
Cell t = q.front() ; q.pop() ;
if (t.xx+1 <= n && !vis[t.xx+1][t.yy]) {
vis[t.xx+1][t.yy] = 1 ;
ma[t.xx+1][t.yy].fx = t.xx ;
ma[t.xx+1][t.yy].fy = t.yy ;
ma[t.xx+1][t.yy].kk = k -- ;
ma[t.xx+1][t.yy].step = t.step + 1 ;
sp += ma[t.xx+1][t.yy].step ;
q.push(ma[t.xx+1][t.yy]) ;
candy.push(ma[t.xx+1][t.yy]) ;
}
if (k == 0) break ;

if (t.yy+1 <= m && !vis[t.xx][t.yy+1]) {
vis[t.xx][t.yy+1] = 1 ;
ma[t.xx][t.yy+1].fx = t.xx ;
ma[t.xx][t.yy+1].fy = t.yy ;
ma[t.xx][t.yy+1].kk = k -- ;
ma[t.xx][t.yy+1].step = t.step + 1 ;
sp += ma[t.xx][t.yy+1].step ;
q.push(ma[t.xx][t.yy+1]) ;
candy.push(ma[t.xx][t.yy+1]) ;
}
}
}

void print_path() {
while (!path.empty()) {
Cell t = path.top() ; path.pop() ;
printf("(%d,%d)%c" , t.xx , t.yy , path.empty()? '\n':' ') ;
}
}

void get_path() {
while (!candy.empty()) {
Cell t = candy.top() ; candy.pop() ;
path.push(t) ;
while (t.xx != 1 || t.yy != 1) {
t = ma[t.fx][t.fy] ;
path.push(t) ;
}
print_path() ;
}
}

int main() {
cin >> n >> m >> k ;
memset(vis , 0 , sizeof(vis)) ;
init() ;
vis[1][1] = 1 ; ma[1][1].kk = k -- ; ma[1][1].step = 1 ;
ma[1][1].fx = 1 ; ma[1][1].fy = 1 ;
sp += ma[1][1].step ;
q.push(ma[1][1]) ;
candy.push(ma[1][1]) ;
bfs() ;
cout << sp << endl ;
get_path() ;
return 0 ;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: