PTA 7-110 Car refueling problem (20 points) (water greedy)

7-110 Car refueling problem (20 points)
Source of title: Wang Xiaodong "Algorithm Design and Analysis"

A car can travel n kilometers after being filled up. There are several gas stations during the journey. Design an effective algorithm to point out which gas stations should stop for refueling, so as to minimize the number of refueling along the way.

Input format: The
first line has 2 positive integers n and k (k<=1000), which means that the car can travel for n kilometers after being filled with fuel, and there are k gas stations on the journey. There are k+1 integers in the second line, which represent the distance between the kth gas station and the k-1th gas station. The 0th gas station represents the departure place, and the car is filled with gas. The k+1th gas station represents the destination.

Output format:
output the minimum number of refueling. If the destination cannot be reached, "No Solution!" is output.

Input example:
7 7
1 2 3 4 5 1 6 6
Output example:
4

#include<bits/stdc++.h>
using namespace std;
int main(){
    
    
	int n,k,num[1009]={
    
    },flag=0,x,total=0;
	cin>>n>>k;
	x=n;
	for(int i=0;i<=k;i++)cin>>num[i];
	for(int i=1;i<k;i++){
    
    
		if(n<num[i]){
    
    
			cout<<"No Solution!"<<endl;
			flag=1;
			break;
		}
		else {
    
    
			n-=num[i];
			if(n<num[i+1]){
    
    
				n=x;
				total++;
			}
		}
	}if(!flag)cout<<total;

	return 0;
	
}

Guess you like

Origin blog.csdn.net/Minelois/article/details/113280525