跳到正文

个人记录

5.18作业

yanziwei88约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟

版本

  1. v1当前

P1347 排序

C++
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+9;
int n,m;
queue<int>q;
vector<int>v[N];
int dp[N];
int in[N],in1[N];
int cnt;
int shu[N];
void topu(){
	memset(dp,0,sizeof(dp));
	memset(shu,0,sizeof(shu));
	cnt=0;
	for(int i=0;i<n;i++){
		in1[i]=in[i];
		if(in[i]==0){
			dp[i]=1;
			q.push(i);
		}
	}
	while(!q.empty()){
		int x=q.front();
		q.pop();
		cnt++;
		for(int i=0;i<v[x].size();i++){
			int y=v[x][i];
			in1[y]--;
			dp[y]=max(dp[y],dp[x]+1);
			if(in1[y]==0){
				shu[x]=y;
				q.push(y);
			}
		}
	}
}
int main(){
	int ans;
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		char x1,c,y1;
		cin>>x1>>c>>y1;
		int x=x1-'A',y=y1-'A';
		in[y]++;
		v[x].push_back(y);
		topu();
		if(cnt<n){
			cout<<"Inconsistency found after "<<i<<" relations."<<endl;
			return 0;
		}else{
			for(int j=1;j<=n;j++){
				if(dp[j]==n){
					string s;
					s=s+char(ans+'A');
					for(int k=1;k<n;k++){
						s=s+char(shu[ans]+'A');
						ans=shu[ans];
					}
					cout<<"Sorted sequence determined after "<<i<<" relations: "<<s<<'.'<<endl;
					return 0;
				}
			}

		}
	}
	cout<<"Sorted sequence cannot be determined.";
	return 0;
}

P2196 [NOIP 1996 提高组] 挖地雷

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+9;
int n,w[N],in[N],dp[N],tu[N];
vector<int>v[N];
queue<int>q;
void topu(){
	for(int i=1;i<=n;i++){
		dp[i]=w[i];
		if(!in[i])q.push(i);
	}
	while(!q.empty()){
		int u=q.front();
		q.pop();
		for(auto i:v[u]){
			if(dp[u]+w[i]>dp[i]){
				dp[i]=dp[u]+w[i];
				tu[i]=u;
			}
			in[i]--;
			if(in[i]==0){
				q.push(i);
			}
		}
	}
	return;
}
void dfs(int x){
	if(tu[x]){
		dfs(tu[x]);
	}
	cout<<x<<' ';
	return;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>w[i];
	}
	for(int i=1;i<=n;i++){
		for(int j=i+1;j<=n;j++){
			bool x;
			cin>>x;
			if(x){
				v[i].push_back(j);
				in[j]++;
			}
		}
	}
	topu();
	int mx=-1e9,v;
	for(int i=1;i<=n;i++){
		if(dp[i]>mx){
			mx=dp[i],v=i;
		}
	}
	dfs(v);
	cout<<endl<<mx<<endl;
	return 0;
}
原文