题目
题解思路
用邻接矩阵存图,用队列来存上车的人,每次下车判断非空,判断有无一起下车的人(这里就需要遍历队列了),人满时不能入队,用指针记录车的位置,每次加上答案即可。
遍历队列小技巧
设置遍历次数(必须是常数)为原来的队列大小,用头入队尾再出队,这样遍历一遍头又变成尾。妙啊
tmp = q.front();
q.pop();
int k = q.size();
for (int i = 0 ; i < k ; i++ )
{
if ( q.front() != tmp )
{
q.push(q.front());
q.pop();
}else
q.pop();
}
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <string>
using namespace std;
int mp[50][50];
int main ()
{
int t;
while(cin>>t)
{
if (t == 0)
break;
int tmp;
for (int i = 0 ; i < t ; i++ )
for (int k = 0 ; k < t ; k++ )
{
cin>>tmp;
mp[i][k] = tmp ;
}
int n ;
string s = "";
queue <int> q;
int ans = 0;
int pot = 0;
cin>>n;
while(n--)
{
cin>>s;
if ( s == "UP" )
{
cin>>tmp;
if (q.size() < 7 && pot != tmp)
{
q.push(tmp);
}
}else
{
if (q.empty())
continue;
tmp = q.front();
q.pop();
int k = q.size();
for (int i = 0 ; i < k ; i++ )
{
if ( q.front() != tmp )
{
q.push(q.front());
q.pop();
}else
q.pop();
}
ans += mp[pot][tmp];
pot = tmp;
}
}
cout<<ans<<"\n";
}
return 0;
}