Judge:https://vjudge.net/problem/UVA-11093
题意:环形跑道上有n个加油小站,第i个加油站可以加油p1加仑,从第i站到下一站需要qi加仑汽油。选择一个起点,使得可以走完一圈回到起点。
从1号加油站开始模拟,如果可以作为起点则输出;如果不可以,说明途中有一站开到下一站时没有油了,那么从这站往前都不可能作为起点。
枚举即可。
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct SNode {
int iIndex;
int iAdd, iNeed;
SNode * pNext;
};
SNode g_arrNode[100011];
int g_iNodeTot;
bool g_arrVisited[100011];
bool Solve(int iStart, int & iStop)
{
SNode * pNode = &g_arrNode[iStart];
int iRest = 0;
bool b = false;
while (true)
{
g_arrVisited[pNode->iIndex] = true;
iRest += pNode->iAdd - pNode->iNeed;
iStop = pNode->iIndex;
if (pNode->iIndex == iStart && b)
return true;
if (iRest < 0)
return false;
pNode = pNode->pNext;
b = true;
}
}
int main()
{
int iDataTot; cin >> iDataTot;
for (int iData = 1; iData <= iDataTot; iData++)
{
memset(g_arrNode, 0, sizeof(g_arrNode));
memset(g_arrVisited, 0, sizeof(g_arrVisited));
cin >> g_iNodeTot;
for (int i = 1; i <= g_iNodeTot; i++)
{
g_arrNode[i].iIndex = i;
cin >> g_arrNode[i].iAdd;
if (i != g_iNodeTot)
g_arrNode[i].pNext = &g_arrNode[i + 1];
else
g_arrNode[i].pNext = &g_arrNode[1];
}
for (int i = 1; i <= g_iNodeTot; i++)
cin >> g_arrNode[i].iNeed;
int iStart = 1, bResult = false;
while (true)
{
if (bResult = Solve(iStart, iStart))
break;
iStart++;
if (g_arrVisited[iStart] || iStart > g_iNodeTot)
break;
}
if (bResult)
printf("Case %d: Possible from station %d\n", iData, iStart);
else
printf("Case %d: Not possible\n", iData);
}
return 0;
}